1. Home
  2. command
  3. Java Random Class Question.?

Java Random Class Question.?

By WinPie Posted in: command

I am trying to generate 5 random numbers using the two classes that i created. I am getting 5 numbers, but they all are zeros.
import java.util.Random;
public class Lottery
{
private int[] num = new int[5];
public int[] Lottery()
{
Random random = new Random();
for(int i = 0; i < num.length; i++){
num[i] = random.nextInt(51);
}
return num;
}
public String toString()
{
String s = "";
for(int i = 0; i < num.length; i++)
s += num[i] + "\n";
return s;
}
}
————————————–…
import java.util.Scanner;
public class Lab1
{
public static void main(String [] args)
{
Lottery lot = new Lottery();
Scanner scan = new Scanner(System.in);
System.out.println("Lottery Numbers: \n" + lot.toString());
}
}

Get Chitika Premium
  1. Peter H Says

    You have confused the Java machine by giving your number-generating method the same name as the class and a return value. Constructors never return a value, so the Java machine actually ran an automatic default blank constructor at the new() statement.
    Rewrite it as
    public Lottery()
    {
    Random random = new Random();
    for(int i = 0; i < num.length; i++){
    num[i] = random.nextInt(51);
    }
    As for your toString method, it is better written as
    public String toString()
    {// writes all numbers on 1 line separated by spaces
    String s = “”;
    for(int i = 0; i < this.num.length; i++)
    s += this.num[i] + ” “;
    s += “n”;
    return s;
    }

Leave a Reply

You must be logged in to post a comment.

More Interesting Things

©2011 Windows Pie, All rights reserved.