Java 用于早期断环
我有一个for循环,如果用户选择,它将被输入Java 用于早期断环,java,loops,Java,Loops,我有一个for循环,如果用户选择,它将被输入 System.out.println("Single Player=1\t Two Player=2\t Report Single Tables=3\t Report all tables=4\t Exit=5"); choice= sc.nextInt(); if(choice ==1){ for (int i = 0; i <= np.length; i++) { if (np[i] == 0) {
System.out.println("Single Player=1\t Two Player=2\t Report Single
Tables=3\t Report all tables=4\t Exit=5");
choice= sc.nextInt();
if(choice ==1){
for (int i = 0; i <= np.length; i++) {
if (np[i] == 0) {
np[i]++;
System.out.print("Enter name:");
String str = sc.nextLine();
player1[i] = str;
break;
}
}}
System.out.println(“单人游戏=1\t双人游戏=2\t报告单人游戏
表=3\t报告所有表=4\t退出=5”);
choice=sc.nextInt();
如果(选项==1){
对于(int i=0;我显示所有代码
否则大家都只是猜测
学习使用step调试器
看看np.length
在i==0
时等于什么,然后你很可能会得到你的答案
说清楚
首先通过looki==0
,很可能也是np.length==0
,但我们完全不知道,因为您没有发布所有相关代码
什么是i==0&&i你应该在choice=sc.nextLine();
之后添加sc.nextLine();
。这会解决你的问题
因为当您输入choice
的编号时,您按enter
。编号由sc.nextInt()读取到choice
,但您的enter
仍在输入流中。
然后,String str=sc.nextLine();
读取您的Enter
并中断循环,而不是等待您输入名称
System.out.println("Single Player=1\t Two Player=2\t Report Single
Tables=3\t Report all tables=4\t Exit=5");
choice= sc.nextInt();
sc.nextLine(); //this line will consume your Enter (end line) char
if(choice ==1){
for (int i = 0; i <= np.length; i++) {
if (np[i] == 0) {
np[i]++;
System.out.print("Enter name:");
String str = sc.nextLine();
player1[i] = str;
break;
}
}
}
System.out.println(“单人游戏=1\t双人游戏=2\t报告单人游戏
表=3\t报告所有表=4\t退出=5”);
choice=sc.nextInt();
sc.nextLine();//此行将使用Enter(结束行)字符
如果(选项==1){
for(int i=0;i)你的括号不正确。你能正确地关闭它们吗?我假设你在最后缺少其中的两个,来关闭for基本块和if基本块。什么是sc
?你也很可能不想要iString str=sc.nextLine();player1[i]=str;
可以替换为:player1[i]=sc.nextLine()
什么是np
?在不知道它包含什么的情况下,我们如何帮助您?请认真思考i=0&&i@辐照猫读是为了理解,我没有问它是为了什么,我问的是,当数组为空且i==0
时,您认为逻辑是什么?我正在与自己争论我应该向上投票还是标记a“不是答案”。决定投票是因为这很有用(虽然不是答案):)你真浪漫,是因为情人节要来吗
System.out.println("Single Player=1\t Two Player=2\t Report Single
Tables=3\t Report all tables=4\t Exit=5");
choice= sc.nextInt();
sc.nextLine(); //this line will consume your Enter (end line) char
if(choice ==1){
for (int i = 0; i <= np.length; i++) {
if (np[i] == 0) {
np[i]++;
System.out.print("Enter name:");
String str = sc.nextLine();
player1[i] = str;
break;
}
}
}