我是Java的初学者,我编写了一个简单的输入java程序。我给用户提供了重复程序的选项,但是它没有正常运行。有人可以指出我的错误吗?
public static void main(String args[]){
char repeat = 0;
Scanner input = new Scanner(System.in);
do{
String word = null;
boolean oneWord = false;
while(!oneWord){
System.out.println("Please enter a word: ");
try{
word = input.nextLine().toLowerCase();
word= word.trim();
int words = word.isEmpty() ? 0 : word.split("\\s+").length;
if(words==1 && word.length()>1 && word.length()<100){
System.out.println("Success");
oneWord = true;
System.out.println("Continue(Y/N)");
repeat = input.next().charAt(0);
}else{
System.out.println("Failure.");
}
} catch (Exception e) {
System.out.println("Exception occurred");
}
}
}while(repeat=='Y'|| repeat=='y');
input.close();
}
答案 0 :(得分:1)
我建议您使用Scanner类的nextLine()函数而不是next()函数。
答案 1 :(得分:0)
即使是副本,也要查看该行
repeat = input.next().charAt(0);
并将其更改为
repeat = input.nextLine().charAt(0);
这将解决您的问题。有关该问题的更多信息,请阅读duplicate link。