【问题标题】:IndexOutOfBoundsException when taking character input from the user从用户获取字符输入时出现 IndexOutOfBoundsException
【发布时间】:2014-12-23 11:54:15
【问题描述】:

第15行ch = s1.charAt(0);, 为什么 ch 没有得到 s1 的第 0 个字,即运算符。

我尝试过不使用 try-catch 方法,但错误与异常有关

现在也不例外,没有错误,但程序不要求操作员,输入后直接 第一个和第二个值,它显示异常“不能这样做”

请留言回复,谢谢

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

【问题讨论】:

  • 我们不知道您的输入是什么,或者您的预期输出。您不费心记录异常的事实也无济于事...请在您的日志记录中包含异常详细信息(例如System.out.println("Error: " + e);
  • 先生,我只是在做普通的计算器,正在学习如何输入字符变量
  • 这并不能帮助我们诊断问题 - 它不能告诉我们您输入的内容或有关异常的任何信息。
  • 嗯...谢谢先生,您能告诉我,parseInt 方法属于哪个类别,我可以在哪里学习它?

标签: java exception charat


【解决方案1】:

您应该将 nextInt 替换为 nextLine

        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() 后面时,它返回一个空字符串,因为它返回包含该整数的行的结尾。当您尝试获取空字符串的第一个字符时,您会得到一个 IndexOutOfBoundsException。

【讨论】:

  • 顺便说一句,这个 parseInt 方法属于哪一类先生?
  • @TakatSingh “属于哪个类别”是什么意思?它是 Integer 类的静态方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-14
  • 2013-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-22
相关资源
最近更新 更多