0
我想寫一個簡單的計算器 我問用戶輸入第一個數字然後第二個和操作是一個字符(即:+, - ,*,/),但我在掃描儀類 上使用同一個對象時得到一個異常,但是當我創建一個新的對象時,它會起作用!與掃描儀類的異常
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) ;
爲什麼?
以前曾經提過幾億次。 – Smutje 2014-10-19 14:34:29