扫描器类的java异常

扫描器类的java异常,java,variables,object,java.util.scanner,Java,Variables,Object,Java.util.scanner,我想写一个简单的计算器 我要求用户先输入第一个数字,然后输入第二个数字,然后输入字符操作(即:+,-,*,/),但在Scanner类上使用相同的对象时出现异常 但是,当我创建一个新对象时,它会工作 Scanner sc = new Scanner (System.in) ; int a , b,res ; char c ; a=0 ; b=0 ; System.out.print("Entrer the frst num ") ; a

我想写一个简单的计算器 我要求用户先输入第一个数字,然后输入第二个数字,然后输入字符操作(即:+,-,*,/),但在Scanner类上使用相同的对象时出现异常 但是,当我创建一个新对象时,它会工作

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) ;
在这种情况下,我会得到以下异常:

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)
但当我改变时,它会起作用:

 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) ;

为什么

在读取第二个int之后添加另一个
sc.nextLine()
。这将消耗该int之后的换行符,这将允许下一个
sc.nextLine()
获得正确的输入,而不是它当前获得的空行。

之前的询问次数达到了无数次。