SamCyanide SamCyanide - 10 days ago 5
Java Question

Scanner needs/is requesting input twice

I'm just writing a small program that receives input from the user then prints it back to them. However, when I run the program it asks for input twice (it prints the initial statement, then once you type and press enter, nothing happens, but if you do it again it works and prints.) The top value apparently has no weight or meaning, as it does not show up, but the second value does get printed well.

package kek;
import java.util.Scanner;

public class Kek {

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

System.out.println("What is kek? (Top, bottom, etc.)");
String s1 = input.next();
if (input.hasNext("kek")) {
System.out.println("No.");
System.exit(0);
} else {
System.out.println(s1 + "kek");
input.close();
}
}
}


Here's the console:

What is kek? (Top, bottom, etc.)
top
top
topkek


and

What is kek? (Top, bottom, etc.)
kek
kek
No.


I'm using eclipse kepler.

Answer

Not sure but is this what you meant ??

public static void main(String[] args) {
    System.out.println("What is kek? (Top, bottom, etc.)");

    Scanner input = new Scanner(System.in);
    String string = input.nextLine();

    if(string.equals("kek")){
        System.out.println("No.");
        System.exit(0);
    }else{
        System.out.println(string + "kek");
        input.close();        
    }    
}

If not then you need to be more specific what you are trying to achieve. As from what you have written now its kind of unclear what you really want

Comments