在Java中第一次跳过控制台?

下面是我在Java中遇到问题的一段代码;它似乎已经为另一个交易了一个问题。由于空白错误,我在检索用户输入时遇到问题;我通过添加“nextLine”而不是“next”来解决这个问题。在Java中第一次跳过控制台?

但是现在,它不会让用户有机会回答第一个问题,它会跳过控制台框并在继续问题2之前输出“错误”,现在用户的第一个控制台框显示出来。

我仔细检查:用“下一个”,第一个问题的控制台出现,但用“nextLine”,它跳过该控制台盒(不给用户输入任何东西的机会),吐出“错误”,然后进入问题二,用户终于可以输入内容。

它为什么这样做?

if(nwb.equalsIgnoreCase("numbers")){ 

System.out.println("You must type in the rules verbatim "+

"(word for word, including punctuation), "+

"as shown on the Student Hand-Out. "+

"Capitalization does not matter.");

int count = 1;

for(int i = 0; i<=(rules.length-1); i++){

System.out.print("Rule #"+count);

String response = console.nextLine().replaceAll(" ","");

if(response.replaceAll(" ", "").equalsIgnoreCase(rules[i].replaceAll(" ", ""))){

System.out.println("CORRECT");

}else{

System.out.println("WRONG\nThe correct wording is: "+rules[i]);

}

count++;

}

}

回答:

它有点繁琐的阅读您的代码,使用{}代码块格式化程序,以便更易于阅读。

尝试使用trim()函数删除输入前后的空格。

这可能是因为您已经在循环中初始化了您的响应字符串,请尝试将其移出并查看它做了什么。希望有帮助。

回答:

String response = console.nextLine(); 

response = response.trim(); //remove spaces

if(response.equalsIgnoreCase(rules[i].trim())){

System.out.println("CORRECT");

}else{

System.out.println("WRONG\nThe correct wording is: "+rules[i]);

}

有几件事要解决。你正在取代空格。并在你的if循环中再次删除空格。并使用修剪()函数删除whitespaces.check与此示例

回答:

对于谁可能关心,我做了一些搜索其他地方,并在几个小时后,我碰到的东西solved it;

基本上,我所做的就是这样的:

if(nwb.equalsIgnoreCase("numbers")){ 

System.out.println("You must type in the rules verbatim (word for word, including puncutation), as shown on the Student Hand-Out. Capitalization does not matter.");

int count = 1;

for(int i = 0; i<=(rules.length-1); i++){

System.out.print("Rule #"+count);

String derpTest = console.nextLine();

String response = console.nextLine().replaceAll(" ","");

if(response.equalsIgnoreCase(rules[i].replaceAll(" ",""))){

System.out.println("CORRECT");

}else{

System.out.println("WRONG\nThe correct wording is: "+rules[i]);

}

count++;

}

}

弦乐derpTest用完了,从我所知道的,所以它的所有收益为String响应。我没有模糊的想法为什么这个工作;我不太明白这个链接是什么意思,所以,如果有人想要解释它,那真是太棒了。感谢所有试图解决这个问题的人,这是一个奇怪的问题。

以上是 在Java中第一次跳过控制台? 的全部内容, 来源链接: utcz.com/qa/257319.html

回到顶部