Reputation:
I made a calculator in C++ and i'm trying to recreate it mirror-like in Java.
There were 2 double variables(double a
and double b
)for the 2 operands and a char(char op
) to put in an if cycle, so for instace if op = '+'
it will cout << a << op << b << "=" << a+b << endl;
.
So i could write 12+2
in the console prompt and see 12+2=14
as output.
Now in Java i have to it one per line:
Scanner Scin = new Scanner(System.in);
System.out.println("OPERATION>");
a = Scin.nextDouble();
op = Scin.next().charAt(0);
b = Scin.nextDouble();
And so i have to write a value and press return each time. How can i input all in one time like C++, and maybe do it in one line of code? Thanks in advance.
Upvotes: 0
Views: 70
Reputation: 33466
You can't read in multiple variables at once using Scanner
, you will have to read them in one at a time. However, there is a nice way to allow the inputs to occur without hitting enter each time or inputting a space: set a different delimiter! The default delimiter is whitespace (which includes newlines), but you could also set it to the word boundary \b
from regex.
Scanner in = new Scanner(System.in).useDelimiter("\\b|\\s+");
Now you can read in 12+2
and it will split up the next
calls where you want them, or you can continue to hit enter, or you can put spaces between the values. Your choice :D
To restore the delimiter to normal afterwards, use in.reset()
.
Edit: To keep the word boundary from splitting the input at a decimal point, use the pattern:
(?<!\\.)\\b(?!\\.)|\\s+
Upvotes: 3