-2

I have been trying to create a program and right now I have trouble with the Scanner in java because in the program the user can input a String and press enter to input it and if the user inputs "exit" like so then the Scanner will close and The loop stops, but It just works for the first Input and gives out a black line every time and if you do enter exit it writes out exit but continues.

here is a code snippit:

    public static void main(String[] args) {
    int i = 0;
    Scanner input = new Scanner(System.in);
    while(input.hasNext() && i<1){  
        System.out.println(input.nextLine());
        if(input.nextLine() == "exit"){
            i++;
        }
    }
    input.close();
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
eyalp55
  • 9
  • 4
  • @MrT you're still doing 2 times `input.nextLine()` ! If I enter as user input "exit" and then "test" it will not stop, it will only display "exit" (and not even display "test" ...) – Kevin Aug 06 '15 at 11:40
  • you right - my mistake. i will delete my answer :) – MrT Aug 06 '15 at 11:43

2 Answers2

0

This works

public static void main(String[] args) {
    int i = 0;
    Scanner input = new Scanner(System.in);
    while(input.hasNext() && i<1){  
        String nextLine = input.nextLine();
        System.out.println(nextLine);
        if(nextLine.equals("exit")){
            i++;
        }
    }
    input.close();
}

The problem was you first did System.out.println(input.nextLIne()) and then did it again in your if statement (hence reading the 2 next lines instead of one).

When inputting "exit" the loop did not stopped because you were comparing a string with ==, you have to compare strings with equals method.

Kevin
  • 2,813
  • 3
  • 20
  • 30
0

I would say use break instead of i++ so it will not wait till for next input after you have entered exit.

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String s;
    while (input.hasNext()) {
        s = input.nextLine(); // input.nextLine(); read single line once.
                              // So you need to assign it to some variable so that you can use it in your if condition.
        System.out.println(s);

        if (s.equals("exit")) { // use equals instead of == also use variable
            break; // so it will not wait for next input to check in while condition hasNext.
        }
    }
    input.close();
}
Naman Gala
  • 4,670
  • 1
  • 21
  • 55