gpt4 book ai didi

Java将哨兵值作为数组输入

转载 作者:行者123 更新时间:2023-11-29 04:28:50 27 4
gpt4 key购买 nike

我需要这个程序接受以下格式的用户输入:“team1 : team2 : score1 : score2”然后将它分配给下面的数组变量,它工作正常但现在我需要在用户输入时这样做“停止”程序显示数组中数据的结果和统计信息。问题是,当您输入停止时,它会尝试将其添加到数组中,但由于我已将输入分成 4 个部分,它只会给我一个错误(异常)

"java.lang.ArrayIndexOutOfBoundsException" error on the "awayteam = results[1];" line.

我的问题是:如果用户输入“停止”,我该如何做到这一点,它不会尝试将其添加到数组中。

// 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

}

}
}

最佳答案

你只需要检查哨兵并在尝试解析它之前跳出 for 循环。

此外,您的另一个 for 循环不正确。您将相同的值放入变量 N 次。 (我添加了一条评论,将其标记为不正确)

System.out.println("please enter match results:");

for (int b = 0; b < 100; b++) {

String s = sc.nextLine();

//CHECK FOR SENTINAL MATCH RIGHT AFTER READING THE NEXT LINE
if (s.equals(SENTINAL)) {
break;
}

String results[] = s.split(" : "); // parse strings in between the
// dash
// character



for (String temp : results) { // You don't need this for loop
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

}

关于Java将哨兵值作为数组输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44763431/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com