i'm having problems creating a program that converts a string of numbers into an array.
i know there is a similar question on here, but all i have to work with is a set of numbers such as [10 15 16 0 57 438 57 18]
heres what i have so far:
import java.util.Scanner;
public class Histogram {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String numbers;
numbers = keyboard.next();
System.out.println(numbers);
int [] n1 = new int [numbers.length()];
for(int n = 0; n < numbers.length(); n++) {
n1[n] = Integer.parseInt(numbers.split(" ")[n]);
}
}
}
this code throws throws an exception:
10 15 20 25 30
10
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Histogram.main(Histogram.java:18)
what am i doing wrong? i want to avoid using commas to separate the elements. can anyone explain why the exception is being thrown and how to fix it? i want to understand more than anything.
Here is what is happening:
Aditionally you should just do this operation numbers.split(" ") once, and then just access it like this:
So basically your for is really something like this:
and then numbers.split(" ") returns only 5 elements, since there is a total of 5 numbers, so when you ask for position 6, the exception is thrown as the array is only of size 5.
I created this class for my own personal use but i think it can help you with your problem.
It can be used like this:
You should split the string once and store the array somewhere.
Here you are iterating up to the number of characters in the string, not the number of space-separated numbers.
Change to:
See it working online: ideone