java为用户重复程序
我是一名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();
}
# 1 楼答案
即使是复制品,也要看一看这条线
把它改成
这会解决你的问题。有关该问题的更多信息,请阅读duplicate link
# 2 楼答案
我建议您使用Scanner类的nextLine()函数,而不是next()函数
See the difference here