2014-12-23 36 views
-4

在第15行ch = s1.charAt(0);, 爲什麼ch沒有得到s1的第0個字,即操作符。IndexOutOfBoundsException當用戶輸入字符時

我試着不使用錯誤是有關異常

,現在也不例外,沒有任何錯誤,但該方案沒有爲運營商和輸入 一日後直接問的try-catch方法,但隨後和第2的值,它顯示了異常「不能這樣做」

請發表您的回覆樣,由於

import java.util.Scanner; 

class apples { 
    public static void calcu() { 
     try{ 
      int a, b; 
      String s1; 
      char ch; 
      Scanner sc = new Scanner(System.in); 
      System.out.print("Enter the 1st value : "); 
      a = sc.nextInt(); 
      System.out.print("Enter the 2nd value : "); 
      b = sc.nextInt(); 
      System.out.print("Enter the operator : "); 
      s1 = sc.nextLine(); 
      ch = s1.charAt(0); 
      System.out.println("yo"); 

       switch(ch){ 
       case '+' : System.out.print("sum is " + (a+b)); 
       case '-' : System.out.print("Substraction is : " +(a-b)); 
       case '*' : System.out.print("Multiplication is : " + (a*b)); 
       case '/' : System.out.print("Multiplication is : " + (a/b)); 
       default : System.out.print("wtf yo"); 
       } 
     } 
     catch(Exception e) { 
      System.out.println("cant do that "); 
     } 

    } 

    public static void main(String args[]) { 
     apples obj = new apples(); 
     obj.calcu(); 
    } 
} 
+0

我們不知道你的輸入是什麼,或者你的預期輸出。你沒有打擾記錄哪些異常* *是沒有幫助,要麼...請在您的日誌記錄異常的詳細信息(如:'的System.out.println(「錯誤:」其實+ E); ') –

+0

我只是做普通計算器先生, 並學習如何輸入字符變量 –

+0

這對我們沒有幫助,雖然診斷的問題 - 它不會告訴我們您輸入的內容,或對任何異常。 –

回答

3

你應該nextLine取代nextInt

 System.out.print("Enter the 1st value : "); 
     a = Integer.parseInt(sc.nextLine()); 
     System.out.print("Enter the 2nd value : "); 
     b = Integer.parseInt(sc.nextLine()); 
     System.out.print("Enter the operator : "); 
     s1 = sc.nextLine(); 
     ch = s1.charAt(0); 

s1 = sc.nextLine();如下b = sc.nextInt(),它返回一個空字符串,因爲它返回包含在INT線的端部。當您嘗試獲取空字符串的第一個字符時,會出現IndexOutOfBoundsException。

+0

是的,先生,你懂了!謝謝 ..! –

+0

BTW哪個類別先生根據本parseInt函數方法下跌呢? –

+1

@TakatSingh你是什麼意思「歸入哪一類」是什麼意思?這是Integer類的靜態方法。 – Eran