因此,我需要为用户创建一个程序来输入匹配分数,并在出现提示时输入“退出”来退出。但是即使没有错误,该代码也不会运行
package Main;
import java.util.Scanner;
public class Assignment {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String[] names = new String[10];
int index = 0;
while (index<10) {
index++;
System.out.print("Home team name: ");
names[index] = keyboard.nextLine();
System.out.print("Away team name: ");
names[index] = keyboard.nextLine();
System.out.print("Enter home score: ");
names[index] = keyboard.nextLine();
System.out.print("Enter away score: ");
names[index] = keyboard.nextLine();
System.out.print("If you would liketo quit type exit: ");
if ("exit".equalsIgnoreCase(keyboard.nextLine()));
keyboard.close();
}
}
}
在这一点上,我对Java和编码的了解甚少,只有非常基本的命令,所以我不知道哪里出了问题。
答案 0 :(得分:0)
进行一些调整,您的程序可以运行。 我没有考虑这是否是一个好的解决方案,但是我认为这是您想要做的。因此,现在您可以改进解决方案,如何退出循环,如何使用扫描仪等等。
package Main;
import java.util.Scanner;
public class Assignment {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String[] names = new String[10];
int index = 0;
while (index<10) {
index++;
System.out.print("Home team name: ");
names[index] = keyboard.nextLine();
System.out.print("Away team name: ");
names[index] = keyboard.nextLine();
System.out.print("Enter home score: ");
names[index] = keyboard.nextLine();
System.out.print("Enter away score: ");
names[index] = keyboard.nextLine();
System.out.print("If you would like to quit type exit: ");
if ("exit".equalsIgnoreCase(keyboard.nextLine())) {
index = 10;
keyboard.close();
}
}
}
}
答案 1 :(得分:0)
在if ("exit".equalsIgnoreCase(keyboard.nextLine()))
之后有分号,因此keyboard.close()
总是被忽略。
删除符合;
的{{1}}
但是关闭输入不会结束while循环。而是添加一个if ("exit".equalsIgnoreCase(keyboard.nextLine()))
命令退出循环并在循环后关闭所有情况下的键盘,不仅限于'exit'