Kyle Goodwin Kyle Goodwin - 5 months ago 30
Java Question

Take a single line input of numbers, and storing it into an array

import java.util.Scanner;

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

System.out.println("Please enter the population of data: ");
int populationOfData = scan.nextInt();

System.out.println("Please enter data separated by spaces: ");
String data = scan.next();

int indexWhiteSpace = data.indexOf(" ");

int[] dataArray = new int[populationOfData];
int tempInt = 0;

for(int index = 0; index < populationOfData; index++)
{
String tempString = data.substring(0, indexWhiteSpace);
data = data.substring(indexWhiteSpace+1, data.length());
tempInt = Integer.parseInt(tempString);

dataArray[index] = tempInt;
indexWhiteSpace = data.indexOf(" ");
}
System.out.println(dataArray[0]);
}
}


I realize there's nothing yet to print out the entire array, as i'm just trying to get it to print anything, but this is continually printing the following errors:

"Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1954)
at HistogramChart.main(HistogramChart.java:22)
"
I cannot figure out why this is saying this.
Please help!

Answer Source

Why not using split ?

class HistogramChart {

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

      System.out.println("Please enter data separated by spaces: ");
      String data = scan.nextLine();

      String tmpDataArray[] = data.split(" ");

      int dataArray[] = new int[tmpDataArray.length];
      for (int i = 0; i < dataArray.length; ++i) {
          dataArray[i] = Integer.parseInt(tmpDataArray[i]);
      }
}