2014-12-23 37 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