我是靠谱客的博主 甜美猫咪,最近开发中收集的这篇文章主要介绍java如何终止while循环,Java while循环没有终止!,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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循环没有终止!所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(40)

评论列表共有 0 条评论

立即
投稿
返回
顶部