-1

My program runs but I'm getting an error String index out of range: 3 When I enter 1 2 for example. I tried changing the values of 1 in partStr = str.substring(lastSpace + 1, x); but that didn't work. Any ideas what I'm doing wrong?

public static void main(String[] args) {
    String str;
    int x;
    int length;
    int start;
    int num;
    int lastSpace = -1;
    int sum = 0;
    String partStr;
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter a series of integers separated by spaces >> ");
    str = keyboard.nextLine();
    length = str.length();
    for (x = 0; x <= length; x++) {
        if (str.charAt(x) == ' ') {
            partStr = str.substring(lastSpace + 1, x);
            num = Integer.parseInt(partStr);
            System.out.println(" " + num);
            sum += num;
            lastSpace = x;
        }
    }
    partStr = str.substring(lastSpace + 1, length);
    num = Integer.parseInt(partStr);
    System.out.println(" " + num);
    sum += num;
    System.out.println("         -------------------" + "\nThe sum of the integers is " + sum);
}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Nitro
  • 87
  • 7
  • At which line do you get that error? – cegredev Apr 08 '20 at 17:42
  • 1
    `for(x = 0; x < length; x++)` - valid string indices are `0` to `length() - 1`. You are calling `str.charAt(str.length())` which is one character too many. – Elliott Frisch Apr 08 '20 at 17:43
  • Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – NotZack Apr 08 '20 at 17:44
  • Nitro - If one of the answers resolved your issue, you can help the community by marking it as accepted. An accepted answer helps future visitors use the solution confidently. Check https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work to learn how to do it. – Arvind Kumar Avinash May 17 '20 at 17:21

3 Answers3

1

You should traverse upto length - 1.

The indexing in String is similar to what happens in arrays.If the length of String is 5 for example,the characters are stored in 0-4 index positions.

Your current loop is traversing beyond the size of the string.

1

str.length() will return the amount of characters of the string, let's say N

for(x = 0; x <= length; x++) will loop N+1 times, instead of N, because the index starts at 0 and you also enter the loop when x is equal to the length

replacing <= with < in the for loop will fix your problem

Cristian
  • 59
  • 6
1

The issue you faced is because you tried to access a character at the index, x (i.e. str.charAt(x)) from str where x is beyond the maximum value of the index in str. The maximum value of the index in str is str.length - 1 whereas the for loop is running up to str.length. In order to fix that problem, you need to change the condition to x < length.

However, even after fixing that issue, your program may fail if any entry is non-integer or if there are multiple spaces in the input. A clean way, including exception handling, to do it would be as follows:

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        String str;
        int sum = 0;
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter a series of integers separated by spaces >> ");
        str = keyboard.nextLine();

        // Split str on space(s) and assign the resulting array to partStr
        String[] partStr = str.split("\\s+");

        // Iterate through partStr[] and add each number to sum
        for (String num : partStr) {
            try {
                sum += Integer.parseInt(num);
            } catch (NumberFormatException e) {
                // Integer::parseInt will throw NumberFormatException for a non-integer string.
                // Display an error message for such entries.
                System.out.println(num + " is an invalid entry");
            }
        }

        // Display the entries and the sum
        System.out.println("Your entries are: " + Arrays.toString(partStr));
        System.out.println("The sum of the integers is " + sum);
    }
}

A sample run:

Enter a series of integers separated by spaces >> 10 a 20 10.5 30 b xy 40 
a is an invalid entry
10.5 is an invalid entry
b is an invalid entry
xy is an invalid entry
Your entries are: [10, a, 20, 10.5, 30, b, xy, 40]
The sum of the integers is 100
halfer
  • 19,824
  • 17
  • 99
  • 186
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110