/ *这是我的错误消息
生命游戏。 多少步骤? 1 网格的大小是多少?五 输入初始网格布局: 线程" main"中的例外情况java.lang.ArrayIndexOutOfBoundsException:0 在GameOfLife.main(GameOfLife.java:23)
- O-- --O -
或类似的东西。我想让每一行成为一个字符串并进入一个数组。这段代码出了什么问题?* /
import java.util.*;
public class GameOfLife {
public static void main(String[] args) {
int steps = 0;
int size = 0;
Scanner sc = new Scanner(System.in);
String [] layout = new String[size];
System.out.println("The Game of Life.");
System.out.print("How many steps in time? ");
steps = sc.nextInt();
System.out.print("What size is the grid? ");
size = sc.nextInt();
System.out.println("Enter the intial grid layout:");
for(int i = 0; i < size; i++) {
layout [i] = sc.nextLine();
}
}
}
答案 0 :(得分:1)
首先阅读size
然后创建数组
// int steps = 0;
// int size = 0;
Scanner sc = new Scanner(System.in);
// String [] layout = new String[size];
System.out.println("The Game of Life.");
System.out.print("How many steps in time? ");
int steps = sc.nextInt();
System.out.print("What size is the grid? ");
int size = sc.nextInt();
String [] layout = new String[size]; // <-- here.
因为您使用的是0
声明中的默认值size
。将来,我建议您尽可能使用狭义范围声明变量。这可以防止这种错误。