我是Java的新手,我正在编写一个程序来打印6个随机数字用于彩票。我收到一个错误,
- 线程“main”中的异常java.lang.RuntimeException:无法编译的源代码 - 无法找到符号 - 符号:可变数字 - 位置:类lotto.Lottery - 在lotto.Lottery.printNumbers(Lottery.java:52) - 在lotto.Lottery.main(Lottery.java:34) -Java结果:1
import java.util.Random;
import java.util.ArrayList;
public class Lottery {
static ArrayList<Integer> lottoNumbers = new ArrayList<Integer>();
static int MAX_NUMBERS = 6;
public static void main(String[] args)
{
generateNumbers();
printNumbers();
}
private static void generateNumbers()
{
int ticketNumber;
Random generateRandomNumber = new Random();
for (int count = 0; count < MAX_NUMBERS; count++)
{
ticketNumber = 1 + generateRandomNumber.nextInt(59);
lottoNumbers.add(new Integer(ticketNumber));
}
}
private static void printNumbers()
{
int count = 0;
for( Integer number : numbers )
{
if (count < 5)
if (count == 4)
System.out.print(number);
else
System.out.print(number + ", ");
else
{
System.out.println("\nPower Ball: " + number);
count++;
}
}
}
}
答案 0 :(得分:2)
您的代码有编译错误,因此程序无法运行:变量numbers
未在任何位置定义。如果要循环生成的数字,请使用lottoNumbers
方法填充的generateNumbers
。你应该在每个元素打印后增加count++
(我强烈建议你在if
语句之后总是使用大括号来避免错误):
int count = 0;
for (Integer number : lottoNumbers) {
if (count < 5) {
if (count == 4) {
System.out.print(number);
} else {
System.out.print(number + ", ");
}
} else {
System.out.println("\nPower Ball: " + number);
}
count++;
}