-2

Ok so i take as an input a list of numbers as a string and i want to take these numbers and create an int array with them.

import java.util.Scanner;



public class StringSplit
{
public static void main(String[] args)
{
int a;
int i = 0;

String s;

Scanner input = new Scanner(System.in);



System.out.println("This programs simulates a queue of customers at registers.");   
System.out.println("Enter the number of registers you want to simulate:"); 
a = input.nextInt();


while(a==0 || a <0){
System.out.println("0 registers or no registers is invalid. Enter again: ");   
a = input.nextInt();
}


 System.out.println("Enter how many customers enter per second.For example: 0 0 1 1 2 2 2 3 3.            
 Enter: ");     
  s = input.next();    
  String[] parts = s.split(" ");      
  System.out.println(parts[1]);       

  for(int n = 0; n < parts.length; n++) {
  System.out.println(parts[n]);
  }

  input.close();



}

}

Everything would be great if i could get the whole array created printed but for some reason i get this:

 Input:
 0 0 1 1 2 2 
 Output:
 0

Thats it. Only the 1st element of the array is printed.Should i try to manually print and element such as parts[1](as i do and i get this:

  Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
  at QueueSimulation.main(QueueSimulation.java:32)

Why is this happening? And more importanly how do i fix it?

1 Answers1

2

If you want to read a line, use:

s = input.nextLine();  

next() returns the value till the first space.

Read more here

Community
  • 1
  • 1
BobTheBuilder
  • 17,650
  • 5
  • 35
  • 58
  • Should i do that and the program ends just after the nextLine comes Up.I was using this before i changed to next so atleast the program doesnt stop... – Aggelos Sfakianos Nov 16 '14 at 17:57
  • @AggelosSfakianos add a termination condition in your code, For e.g. if user types exit you stop your program (meaning don't process let main method finish) – mprabhat Nov 16 '14 at 18:00