简体   繁体   English

Java 字符串错误越界

[英]Java String Error Out Of Bounds

I am exercising for my course in java and the task is to write a program which has the input of a list separeted with spaces.我正在练习我的 Java 课程,任务是编写一个程序,该程序的输入是用空格分隔的列表。 And the key is to turn the list around, ie put the first place on the last second on the one before last and truncate the negatives.关键是翻转列表,即将最后一秒的第一名放在最后一秒之前并截断负数。 But I am keep getting this error of StringIndexOutOfBounds.但我不断收到 StringIndexOutOfBounds 的这个错误。 What seems to be the problem?似乎是什么问题?

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

I suspect your StringIndexOutOfBounds comes from the fact you are iterating from index 0 to index input.length , so 1 too many.我怀疑您的StringIndexOutOfBounds来自您从索引 0 迭代到索引input.length ,所以 1 太多了。

For the sake of charAt the Strings in Java are 0-indexed, so you start counting from 0 (what you would call 'first' in plain English).为了charAt ,Java 中的字符串是 0 索引的,所以你从 0 开始计数(你会用简单的英语称之为“第一”)。 In such a situation, the last character is at index length-1 .在这种情况下,最后一个字符位于索引length-1

So, to be specific.所以,具体来说。 Your next thing to fix is the condition in the while loop.您接下来要解决的问题是while循环中的条件。 I think your intention was to say:我想你的意图是说:

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

Any String has characters from index 0 to length-1.任何字符串都有从索引 0 到长度 1 的字符。 If you would try to do charAt(length), you would end up with StringIndexOutOfBounds.如果您尝试执行 charAt(length),您最终会得到 StringIndexOutOfBounds。

Change the while line to below & it should work:将 while 行更改为下面,它应该可以工作:

while (counter<input.length()){

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

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