-2

I am new to Java and am having trouble with this particular for loop. Everytime I run the loop and enter a number that is not 1 or 2, the loop displays: "Please choose a correct option". What could be the cause of this?

public class Kbin {

public static void main (String args[]) throws java.io.IOException {

int option;
int i = 0;


System.out.println("What would you like help with?");
System.out.println("\t1.  If statement");
System.out.println("\t2.  Switch statement");
option = (char) System.in.read();


// loop:    
for(i = 0; option != 1 & option != 2; i ++){

    System.out.println("What would you like help with?");
    System.out.println("\t1.  If statement");
    System.out.println("\t2.  Switch statement");
    option = (char) System.in.read();

    switch(option){
        case '1':
            System.out.println("here is how you do an if statement");
            i += 1;
            break loop;
        case '2':
            System.out.println("Here is how you do a switch statement");
            i += 1;
            break loop;
        default:
            System.out.println("Please choose a correct option.");

            continue;
        }

    }
}
}
Coder
  • 1,175
  • 1
  • 12
  • 32
p h
  • 1
  • 1
    Don't read in input with `System.in.read()` as that is a very brittle way to do this. Instead use a Scanner or BufferedReader. Also, you shouldn't be using goto statements. Use real loop structures. – Hovercraft Full Of Eels Sep 26 '17 at 00:37
  • 3
    *Everytime I run the loop and pick a number that is not 1 or 2 will cause the loop to display "Please choose a correct option".* Isn't that the point? – shmosel Sep 26 '17 at 00:41
  • Sorry it displays it two times in a row. – p h Sep 26 '17 at 00:55
  • You have two copies of your `System.out.println(...)` instructions, and two copies of the `System.in.read()`. – AJNeufeld Sep 26 '17 at 00:57
  • 1
    What's your input? – shmosel Sep 26 '17 at 00:58
  • 1
    Hint: If you you type a "3" followed by the return key, the `InputStream` will contain the characters `'3'` and `'\n'`. – AJNeufeld Sep 26 '17 at 01:01

1 Answers1

-1

Option variable is not getting the correct value that u expect it to hold. As by seeing your code the user would enter either 1 or 2, then you are trying to convert it into char thats where the problem is. Try to take int as input Scanner input = new Scanner(System.in); option = input.nextInt();