【发布时间】:2017-06-26 15:40:32
【问题描述】:
我需要这个程序接受以下格式的用户输入:“team1:team2:score1:score2”然后将其分配给下面的数组变量,这工作正常,但现在我需要在用户输入时这样做“停止”程序显示数组中数据的结果和统计信息。 问题是,当您输入 stop 时,它会尝试将其添加到数组中,但由于我已将输入分成 4 部分,它只会给我一个错误(异常)
“awayteam =”上的“java.lang.ArrayIndexOutOfBoundsException”错误 结果[1];”行。
我的问题是:我怎样才能做到,如果用户输入“停止”,它不会尝试将其添加到数组中。
// Sample input: Chelsea : Arsenal : 2 : 1
public static final String SENTINEL = "stop";
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String hometeam = new String();
String awayteam = new String();
String homescore = new String();
String awayscore = new String();
int result0;
int result1;
int sum = 0;
System.out.println("please enter match results:");
for (int b = 0; b < 100; b++) {
String s = sc.nextLine();
String results[] = s.split(" : "); // parse strings in between the
// dash
// character
for (String temp : results) {
hometeam = results[0];
awayteam = results[1];
homescore = results[2];
awayscore = results[3];
}
//convert 'score' strings to int value.
result0 = Integer.valueOf(results[2]);
result1 = Integer.valueOf(results[3]);
//stop command
if (s.equals(SENTINEL)) {
System.out.println("stopped");
}
// print results
}
}
}
【问题讨论】:
-
在您尝试分配变量之前检查 SENTINEL,就在您阅读下一行之后。您可以在 if 语句中包围分配,或者您可以简单地中断。
标签: java arrays loops sentinel