Trent Shailer Trent Shailer - 1 month ago 9
Java Question

Inputing and Java Scanners

I want to make it so when you type yes in the console it prints out text.
The input line:

if (input == yes) {
System.out.println("Test");
}


I just have no clue what to do, I have worked with inputting numbers:

System.out.println("You continue down the road and find yourself at the foot of a large hill with a tunnel going through it.");

System.out.println("[1] Go up the hill.");

System.out.println("[2] Go through the tunnel.");

input = s.nextInt();

if (input == 2) {

System.out.println("You walked swiftly through the tunnel and find yourself back at the start");
continue;
}

Answer

Your first example with the user input being yes and printing text can be achieved using the nextLine() from the Scanner.

 Scanner scan = new Scanner(System.in);
        String str;
        System.out.print("Do you want to test me? (yes/no) ");
        str = scan.nextLine();
        if (str.equals("yes")){ //comparing strins with .equals()
            System.out.println("Test");
        }else {
            //do something
        }

but you want to give more options like your second then you can try this below.

 Scanner scan = new Scanner(System.in);

        //String str; if you want to read strings uncomment here and comment num
        int num;

        System.out.println("You continue down the road and find yourself at the foot of a large hill with a tunnel going through it.\n" +
                "1. Go up the hill.\n2. Go through the tunnel.");

        //str = scan.nextLine(); if you uncomment this comment num
        num = scan.nextInt();
        if (num == 1){ //comparing numbers with ==
            System.out.println("well go up up!!");
        }else if (num == 2){
            System.out.println("You walked swiftly through the tunnel and find yourself     back at the start");
        }else {
            System.out.println("Not in the range");
        }
Comments