概述
I have a code in Java for which while loop is not terminating.. If I use a file instead of Std, I get correct result.. Please point out my mistake.. Code:public static void main(String args[] ) throws Exception {
int y;
int n;
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
y = 0;
n = 0;
while(sc.hasNextLine()){
String c = sc.next();
Pattern p = Pattern.compile("[0-9]{1,2}");
Matcher m = p.matcher(c);
if(m.matches()){
if(c.equals("19") || c.equals("20")){
y += 4;
}
else{
n += 3;
}
}
}
System.out.println("Y Is: " + y + "N is : " + n);
System.out.println(y > n ? "Date" : "No Date");
}Thanks in Advance!
What I have tried:
Taking Scanner input inside while loop!
解决方案
Ummm... There is no such thing as NOT a next line when input is coming from the console.
Instead of checking for hasNextLine, you might want to check for an empty string returned to signal a quit or something like that.
Quote:If I use a file instead of Std, I get correct result..
Your mistake is that the keyboard never ends, the fact that you wait in front of keyboard is not an end of input.
Back in time, when I did this in C, the keyboard end of file was Ctrl-Z.
If it don't work, you will have to think about a special input that will act as an end of file.
最后
以上就是甜美猫咪为你收集整理的java如何终止while循环,Java while循环没有终止!的全部内容,希望文章能够帮你解决java如何终止while循环,Java while循环没有终止!所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复