0

I am having trouble with delimiters. My code is as follows:

Scanner in=new Scanner(System.in);
in.useDelimiter("\\D");
int x,y,z;
System.out.println("Enter 3 digits:  ");
x=in.nextInt();
y=in.nextInt();
z=in.nextInt();
System.out.println(x + " " + y + " " + z);
in.close();

Pardon my lack of experience with delimiters, but I can only get my program to separate input with 1 character, not two. The program must be able to take input as follows:

either 1 2 3 or 1, 2, 3. currently it can handle 1 2 3 and 1,2,3 but not 1, 2, 3

The extra spaces in the last case must be throwing it off. How do you handle this?

Additionally, I must be able to take in a variable number of integers as input, up to 100 integers, and insert them into a queue. Obviously the three variables I have defined are not enough but clearly defining 100 would also be overkill. What is the most efficient way to handle this? Thanks in advance.

avojak
  • 2,067
  • 2
  • 26
  • 28
Wrobbe
  • 9
  • 1

2 Answers2

2

Try changing the Delimiter to \\D+ (i.e. in.useDelimiter("\\D+");).

EDIT:
At the moment, you are asking the delimiter to split on a single non-digit character. By adding the + you are telling it to split on continuous blocks of non-digit characters. The delimiter is a regular expression, and there's more information on those here: www.regular-expressions.info/tutorial.html

Dawood ibn Kareem
  • 68,796
  • 13
  • 85
  • 101
James Baker
  • 983
  • 12
  • 35
  • At the moment, you are asking the delimiter to split on a single non-digit character. By adding the `+` you are telling it to split on continuous blocks of non-digit characters. The delimiter is a regular expression, and there's more information on those here: http://www.regular-expressions.info/tutorial.html – James Baker Nov 10 '16 at 08:41
  • Thank you. Much better now. – Dawood ibn Kareem Nov 10 '16 at 08:58
0
Scanner in=new Scanner(System.in);
in.useDelimiter("\\D+");
int n=5; // Here you should define your limit
int[] data=new int[n];
for(int i=0;i<data.length;i++)
{
    System.out.println("Enter "+i+" digit:  ");
    data[i]=in.nextInt();
}

// print store value
for(int i=0;i<data.length;i++)
{
    System.out.println(data[i]);
}
in.close(); 

Above code helps you to get n no. of integer inputs

denvercoder9
  • 2,764
  • 3
  • 24
  • 38
Keval Pithva
  • 560
  • 1
  • 5
  • 20