【问题标题】:How do I debug this error regarding with the string and int如何调试有关字符串和 int 的此错误
【发布时间】:2018-10-21 08:43:40
【问题描述】:

我想知道输入数字的位置,所以我决定使用 parse 将 String 类型转换为 int 数据类型,源代码如下:

public static void main (String [] Args) {
    Scanner input = new Scanner (System.in);
    String x = "0" ;
    int number = Integer.parseInt(x);

    System.out.print("\nEnter 5 numbers: ");
    number = input.nextInt();

    if ((x.charAt(0) == x.charAt (4)) && (x.charAt(1) == x.charAt(3))) {
        System.out.print("The set of numbers is equal to its original value");
    } else {
        System.out.print("The set of numbers is not equal to its original value");
    }   
}   

我编译文件后,它不会运行,出现这个错误

线程“主”java.lang.StringIndexOutOfBoundsException 中的异常: 字符串索引超出范围:4 在 java.base/java.lang.StringLatin1.charAt(未知来源) 在 java.base/java.lang.String.charAt(未知来源) 在activity10.main(activity10.java:12)

【问题讨论】:

  • 您的字符串 x 为 '0' 但您尝试从索引 4 获取值。您可以使用任何编辑器调试选项..
  • 请重新格式化您帖子中的代码。
  • 我不明白你的程序试图做什么(它的逻辑与输出不对应)。也许退后一步,重新考虑你的算法。
  • 如何得到 x.charAt(4) 而 x 的大小只有一个???

标签: java


【解决方案1】:

charAt(i) 方法返回 String 的第 i-th 个字符(从索引 0 开始)。这意味着如果您想调用yourString.charAt(k)yourString 必须至少有 k+1 个字符。

根据你的代码

String x = "0";

x永远是 "0"。因此,对于 i > 0 的任何调用 x.charAt(i) 都会导致 StringIndexOutOfBoundsException

更新

下面的代码能满足你的需要吗?

public static void main(String[] args) {
    Scanner input = new Scanner (System.in);

    System.out.print("\nEnter 5 numbers: ");
    String x = input.next();

    if ((x.charAt(0) == x.charAt (4)) && (x.charAt(1) == x.charAt(3))) {
        System.out.print("The set of numbers is equal to its original value");
    } else {
        System.out.print("The set of numbers is not equal to its original value");
    }
}

【讨论】:

  • 我更新了我的答案。现在您在同一行中输入所有数字。
  • 哦我忘了,这个程序想知道输入的数字是否是回文,所以我该怎么办(抱歉代码有点乱)
  • 请考虑一下您希望程序做什么。然后更新您的问题并写下您已经尝试过的内容以及您目前的具体问题。这将增加您获得完整答案的机会。
【解决方案2】:

您正在尝试使用 扫描仪输入

获取输入编号

那个,你不需要这些行

String x = "0" ;
int number = Integer.parseInt(x);

你需要做的就是先得到数字

int number1 = input.nextInt();
int number2 = input.nextInt();
int number3 = input.nextInt();
int number4 = input.nextInt();
int number5 = input.nextInt();

然后从数字的比较开始。

此外,您可以阅读一些 Java 教程,然后开始编码,因为它可以帮助您了解编程基础知识

【讨论】:

    猜你喜欢
    • 2022-10-25
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多