0
do
    {

       // asking user choices
       choice = Integer.parseInt(br.readLine());

        switch(choice)
        {

           // doing something
        }

        System.out.println("Do you want to continue?");
        System.out.println("(Y/N)");
        ans = (char) br.read(); 
    }
    while(ans == 'y' || ans == 'Y');

I am using eclipse; I want to check whether the user want to re-enter the switch case by entering his answer by a char 'y' || 'Y'. But whenever i enter the char 'Y' it enters the do loop but also executes the choice variable. And as the choice variable is int; it throws number format exception.

Do you want to continue?
(Y/N)
y
// prints all  my switch options
Exception in thread "main":
 java.lang.NumberFormatException: For input string: ""
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:592)
    at java.lang.Integer.parseInt(Integer.java:615)
    at ArithemeticOperations.main(ArithemeticOperations.java:45)
saify
  • 70
  • 1
  • 9
  • because once you press enter you also print carriage return and line break as well which are 2 more characters. you will need to check if the entered char is one of them to only execute the switch if its an int – XtremeBaumer Dec 12 '16 at 07:18
  • could you paste your whole code? – sameera sy Dec 12 '16 at 07:21
  • @ScaryWombat Technically this isn't about `Scanner`, but I guess the issue is the same. – shmosel Dec 12 '16 at 07:25

2 Answers2

2

See that "input string" part of the message? It tells you that the input to the parseInt function is empty. And it's empty because it's the newline after you entered your y. You need to read a whole line for the "continue" answer, and get the character from that full line.

Some programmer dude
  • 363,249
  • 31
  • 351
  • 550
0

@SomeProgrammerDude already explained the reason behind your problem. So, i am not repeating it. You can modify your code as given below.

String ans;
do{
    // asking user choices
    choice = Integer.parseInt(br.readLine());
    switch(choice){
       // doing something
    }
    System.out.println("Do you want to continue?");
    System.out.println("(Y/N)");
    ans = br.readline(); 
}while(ans.toLowerCase().equals("y"));
Wasi Ahmad
  • 27,225
  • 29
  • 85
  • 140
  • Thanks for taking time to answer. Though i would mark @SomeProgrammerDude as the answer for this question; cause it explains the technical aspect of my problem. Nonetheless thanks again for providing the solution to my work. – saify Dec 12 '16 at 09:12