Java Delimiter Issue
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.
Try changing the Delimiter to D+
(ie 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
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
链接地址: http://www.djcxy.com/p/78360.html上一篇: 将一条线分割成java中的对象
下一篇: Java分隔符问题