简体   繁体   English

用Java一次输入不同的变量类型

[英]Inputting different variable types in one time in Java

I made a calculator in C++ and i'm trying to recreate it mirror-like in Java. 我做了C ++中的计算器和我试图重新建立镜像像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; 对于2个操作数,有2个double变量( double adouble b ),并且将一个char( char op )放入了if循环,因此对于instace if op = '+'它将提示cout << a << op << b << "=" << a+b << endl; .

So i could write 12+2 in the console prompt and see 12+2=14 as output. 所以我可以在控制台提示符下写12+2并看到12+2=14作为输出。

Now in Java i have to it one per line: 现在在Java中,我必须每行一个:

    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? 我输入都在同一个时间像C ++和如何可能做到这一点的一行代码? Thanks in advance. 提前致谢。

You can't read in multiple variables at once using Scanner , you will have to read them in one at a time. 您无法使用Scanner一次读取多个变量,而必须一次读取一次。 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. 缺省的分隔符是空白(包括换行符),但你也可以将它设置为字边界\\b从正则表达式。

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. 现在您可以阅读12+2 ,它将在您需要的位置拆分next调用,或者您可以继续按Enter,或者可以在值之间放置空格。 Your choice :D 您的选择:D

To restore the delimiter to normal afterwards, use in.reset() . 要将分隔符恢复到正常状态,请使用in.reset()

Edit : To keep the word boundary from splitting the input at a decimal point, use the pattern: 编辑 :为了防止单词边界在小数点处拆分输入,请使用以下模式:

(?<!\\.)\\b(?!\\.)|\\s+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM