user3404250
user3404250

Reputation: 23

Trouble With hasNext() in Java

I'm trying to write a program that reads pairs of words and outputs the number of pairs of identical words. It's assumed an even number of words are inputted. When I run my code, it doesn't output anything. It appears to be continually running. When I press Ctrl-Z after I'm done inputting words, it either returns "0" or nothing at all. Any thoughts on how to make my program run properly? Thanks.

EDIT: it runs fine in the command prompt, but not in Eclipse.

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int counter = 0;

        while (input.hasNext()) { 

            String string1, string2; 
            string1 = input.next();
            string2 = input.next();

            if (string1.equals(string2)) {
                ++counter;  
            }   

        }
        System.out.println(counter);
    }

Upvotes: 0

Views: 596

Answers (2)

fzappaandthem
fzappaandthem

Reputation: 11

It doesn't really work in eclipse for me (nor does in netbeans for what i have read), to test if your code actually works well you should do this: (In windows) Open a command prompt ( execute ... "cmd" + Enter ) then compile your class or classes with

javac YourClass.java

if no errores it will just let you type a new command with no messages and then

java YourClass

then you can try the Ctrl + z in windows (ctrl + d in linux) which will print the ^Z character and then hit enter.

Hope it helped.

Upvotes: 0

AlexR
AlexR

Reputation: 115378

You are asking hasNext() once, but then calling next() twice. The second next() can fail if there are no more elements.

Upvotes: 2

Related Questions