繁体   English   中英

Java 字符串错误越界

[英]Java String Error Out Of Bounds

我正在练习我的 Java 课程,任务是编写一个程序,该程序的输入是用空格分隔的列表。 关键是翻转列表,即将最后一秒的第一名放在最后一秒之前并截断负数。 但我不断收到 StringIndexOutOfBounds 的这个错误。 似乎是什么问题?

public static void main(String args[])
{ 
    Scanner in = new Scanner (System.in);
    System.out.println("Insert the list: ");
    String input = in.nextLine();

    String out = out(input);

    System.out.println(out);
}

public static String out (String input){
    String reverse = "";
    int counter = 0;

    while (counter<=input.length()){/*
        String min = input.charAt(counter) +                            input.charAt(counter+1);
        int num = Integer.parseInt(min) ;
        if ( num>=0 ){*/
            reverse+= input.charAt(counter);
            counter++;
        /*}*/
    }
    return reverse;
}

我怀疑您的StringIndexOutOfBounds来自您从索引 0 迭代到索引input.length ,所以 1 太多了。

为了charAt ,Java 中的字符串是 0 索引的,所以你从 0 开始计数(你会用简单的英语称之为“第一”)。 在这种情况下,最后一个字符位于索引length-1

所以,具体来说。 您接下来要解决的问题是while循环中的条件。 我想你的意图是说:

while (counter < input.length()) {
...

任何字符串都有从索引 0 到长度 1 的字符。 如果您尝试执行 charAt(length),您最终会得到 StringIndexOutOfBounds。

将 while 行更改为下面,它应该可以工作:

while (counter<input.length()){

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM