Reputation: 23
I am trying to read multiple variables from the console with the scanner in only one line (separated with a blank space).
if I type:
int hight = Integer.parseInt(reader.nextLine());
int width = Integer.parseInt(reader.nextLine());
int depth = Integer.parseInt(reader.nextLine());
then it displays my numbers (for example 1,2,3) like this:
1
2
3
but I would want it to display my numbers like that: 1 2 3
Can someone help me?
Upvotes: 2
Views: 3436
Reputation: 81
For input in single line in space separated format. You can do that using Scanner and BufferReader in Java. 1. Scanner class
Scanner sc = new Scanner(System.in);
int[] integers;
String input = sc.nextLine();
String[] strs= input().split(" ");
for(int i=0;i<strs.length;i++){
integers[i]=Integer.parseInt(strs[i]);
}
2. BufferReader Class
BufferReader br = new BufferReader(new InputStreamReader(System.in));
int[] integers;
String input = br.readLine();
String[] strs= input().trim().split("\\s+");
for(int i=0;i<strs.length;i++){
integers[i]=Integer.parseInt(strs[i]);
}
Upvotes: 0
Reputation: 3609
To input all 3 values in one line you can use. . readInt()
three times instead of using .readNextLine()
. That way you can put your input like this 1 2 3
and after pressing Enter
on the keyboard (which is by default used to end the input) you get what you were asking for.
If your intention was to get an output in one line instead of multiline one, you should use other version of method printing to the console:
System.out.print(height + " " + weight + " " + depth)
System.out.println()
prints the next line character after its argument, System.out.print()
doesn't.
Upvotes: 0
Reputation: 802
As per your comment you can simply read numbers as integers like :
Scanner br =new Scanner(System.in);
int a=br.nextInt();
int b=br.nextInt();
int c=br.nextInt();
Give input as 1 2 3.
Upvotes: 0
Reputation: 271625
One way to do this is to use nextInt
instead of nextLine
:
int hight = reader.nextInt();
int width = reader.nextInt();
int depth = reader.nextInt();
Your input can then be like this:
1 2 3
Note that you have to enter all three numbers before pressing ENTER, or else your input will look like this again:
1
2
3
Another way to do this is to use a regex to specify the exact format that you want your input to be in, call nextLine
, and match the line that the user entered to the regex pattern:
Matcher matcher = Pattern.compile("(\\d+)\\s+(\\d+)\\s+(\\d+)").matcher(reader.nextLine());
if (matcher.matches()) {
int height = Integer.parseInt(matcher.group(1));
int width = Integer.parseInt(matcher.group(2));
int depth = Integer.parseInt(matcher.group(3));
} else {
// input was invalid!
}
Upvotes: 4