我是Java的新手,在创建一个程序打印彩票的6个随机数时,我收到ArrayIndexOutOfBounds
错误,我无法弄清楚如何修复。这就是我所拥有的。
import java.util.Random;
public class DebugMeOne {
static int[] lottoNumbers = new int[6];
public static void main(String[] args)
{
generateNumbers();
printNumbers();
}
private static void generateNumbers()
{
int ticketNumber;
Random generateRandomNumber = new Random();
for (int count = 0; count < lottoNumbers.length + 1; count++)
{
ticketNumber = 1 + generateRandomNumber.nextInt(59);
lottoNumbers[count] = ticketNumber;
}
}
private static void printNumbers()
{
for (int count = 0; count < lottoNumbers.length + 1; count++)
{
if (count < 5)
if (count == 4)
System.out.print(lottoNumbers[count]);
else
System.out.print(lottoNumbers[count] + ", ");
else
System.out.println("\nPower Ball: "
+ lottoNumbers[count]);
}
}
}
我还有另一个程序,我必须为同样的事情创建,只是一点点不同的代码。我也遇到了错误:
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 ) // enhanced for loop
{
if (count < 5)
if (count == 4)
System.out.print(number);
else
System.out.print(number + ", ");
else
{
System.out.println("\nPower Ball: " + number);
count++;
}
}
}
}
在此我收到此错误:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code
cannot find symbol
symbol: variable numbers
location: class debugmetwo.DebugMeTwo
at debugmetwo.DebugMeTwo.printNumbers(DebugMeTwo.java:52)
at debugmetwo.DebugMeTwo.main(DebugMeTwo.java:34)
Java Result: 1
答案 0 :(得分:0)
你的循环条件应该是:
for (int count = 0; count < lottoNumbers.length; count++)
lottoNumbers
的有效索引来自0
到lottoNumbers.length - 1
。
答案 1 :(得分:0)
您的for
循环次数超过了数组length
。 for循环都应该像
for (int count = 0; count < lottoNumbers.length; count++)
此外,您不应该对length
比较中使用的count
值(5,4)进行硬编码以打印逗号。使用length
属性
for (int count = 0; count < lottoNumbers.length; count++)
{
if (count < lottoNumbers.length - 1) {
System.out.print(lottoNumbers[count]);
System.out.print(count == lottoNumbers.length - 2 ? "" : ", ");
} else {
System.out.println("\nPower Ball: "
+ lottoNumbers[count]);
}
}