0

I'm trying to write a simple calculator I asked the user to enter the first number then the second and the operation that is a character (ie : +,-,*,/) but i get an exception when using the same object on Scanner class however when I create a new object it works !!

Scanner sc = new Scanner (System.in) ; 
    int a , b,res ; 
    char c ; 
    a=0 ; 
    b=0 ; 

    System.out.print("Entrer the frst num ") ;
    a = sc.nextInt() ; 
    System.out.print("entre the second : ") ; 
    b= sc.nextInt() ; 
    System.out.print("the operation plz  ") ; 
    c = sc.nextLine().charAt(0) ;

In this case i get this exception :

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at javatut.tut.main(tut.java:21)

but it work when i change :

 Scanner sc = new Scanner (System.in) ; 
 Scanner sc2 = new Scanner (System.in) ;
    int a , b,res ; 
    char c ; 
    a=0 ; 
    b=0 ; 

    System.out.print("Entrer the frst num ") ;
    a = sc.nextInt() ; 
    System.out.print("entre the second : ") ; 
    b= sc.nextInt() ; 
    System.out.print("the operation plz  ") ; 
    c = sc2.nextLine().charAt(0) ;

Why ??

aouakki
  • 310
  • 5
  • 16

1 Answers1

0

Add another sc.nextLine() after reading the second int. This would consume the newline that follows that int, which would allow the next sc.nextLine () to get the correct input, instead of the empty line it currently gets.

Eran
  • 387,369
  • 54
  • 702
  • 768