Java while循环没有终止! [英] Java while loop not terminating!
问题描述
我有一个Java代码,其中while循环没有终止..如果我使用文件而不是Std,我得到正确的结果..请指出我的错误..代码:
public static void main(String args [])抛出异常{
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();
模式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是:+ y +N是:+ n);
System.out.println(y> n?Date:No Date);
}
提前致谢!
我的尝试:
在循环中输入扫描仪输入!
嗯...没有这样的输入来自控制台时不是下一行的东西。
您可能想要检查返回的空字符串以表示退出,而不是检查hasNextLine或类似的东西。
Quote:如果我使用的是文件而不是Std,我会得到正确的结果..
你的错误是键盘永远不会结束,你在键盘前等待的事实并不是输入的结束。
返回时间,当我在C中这样做时,文件的键盘末端是Ctrl-Z。
如果它不起作用,你将不得不考虑一个特殊的输入,它将作为一个结束文件。
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循环没有终止!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!