java如何终止while循环,Java while循环没有终止!

这篇博客讨论了一个Java代码中while循环无法正常结束的问题。作者在使用Scanner从标准输入读取时遇到问题,当尝试从文件读取时,代码能够得到正确结果。错误在于键盘输入不会像文件那样自动结束,导致while循环无限运行。解决方案可能是检查是否读取到空字符串作为输入结束的标志。
摘要由CSDN通过智能技术生成

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值