【发布时间】:2015-09-21 13:20:27
【问题描述】:
编辑
我有输入 5 3,其中 10 是每行的字符数量,5 (StartA) 是该行中 * 的位置。
我需要将此输入保存在布尔数组中,以便保存 {假,假,真,假,假} 目前,程序在执行时会给出一个 nullPointerExeption: CurrentState[i] == true
请您解释一下我是如何编程的。
class Program{
Scanner sc = new Scanner(System.in);
int L; // #characters per line
int G; // # lines
int Start; // Starting position
int i; // position of character calculated
int k; // Position in new line
int j; // Row working
String choice; // choice which program to execute
boolean firstLine[] = new boolean[L+1];
boolean nextGen[] = new boolean[L+1];
void input() {
L = sc.nextInt(); // # Characters per line
G = sc.nextInt(); // # lines
Start = sc.nextInt(); // Characters which is a * in first line
}
// output for first line
void line() {
for (i=0; i<L+1; i++) {
if (i == Start-1) {
CurrentState[i] = true;
System.out.print("*");
} else if (i==L) {
System.out.println("");
} else {
CurrentState[i] = false;
System.out.print(".");
}
}
}
// rules for calculating the next line
void rules() {
for ( k=0; k<L-1; k++) {
for ( i=1; i<L-1; i++) {
if (CurrentState[i-1] == true && CurrentState[i]== true && CurrentState[i+1] == true) {
nextGen[k] = false;
} else if (CurrentState[i-1] == true && CurrentState[i] == true && CurrentState[i+1] == false) {
nextGen[k] = true;
} else if (CurrentState[i-1] == false && CurrentState[i] == true && CurrentState[i+1] == true) {
nextGen[k] = true;
} else if (CurrentState[i-1] == false && CurrentState[i] == false && CurrentState[i+1] == false) {
nextGen[k] = false;
} else if (CurrentState[i-1] == true && CurrentState[i] == false && CurrentState[i+1] == true) {
nextGen[k] = true;
} else if (CurrentState[i-1] == false && CurrentState[i] == false && CurrentState[i+1] == true) {
nextGen[k] = true;
} else if (CurrentState[i-1] == true && CurrentState[i] == false && CurrentState[i+1] == false) {
nextGen[k] = true;
} else if (CurrentState[i-1]== false && CurrentState[i] == true && CurrentState[i+1]== false) {
nextGen[k] = false;
}
}
return true;
}
}
// gives output for line 2 till G.
void nextLine() {
for (j=0; j<G-1; j++){
for (k=0; k<L; k++){
if (nextGen[k] == true) {
System.out.print("*");
} else if (k==L-1) {
System.out.println("");
} else {
System.out.print(".");
}
}
}
}
void run() {
input();
line();
rules();
nextLine();
}
public static void main(String[] args) {
new Program().run();
}
}
【问题讨论】:
-
你初始化 CurrentState 了吗?您需要像这样声明数组,然后才能使用它:
boolean CurrentState[] = new boolean[x],其中x是您想要的元素数。 -
好的。我需要把这条线放在哪里?
-
@Peter 在类的构造函数或属性声明中。