Click here to Skip to main content
15,894,460 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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!
Posted
Updated 11-Mar-18 13:47pm
Comments
Richard MacCutchan 12-Mar-18 5:11am    
You need to add a check for some special string that tells the program there is no more input.

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.
 
Share this answer
 
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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900