[英]Java: How to have two or more inputs in one line in the console
I am new to java and I wrote a Basic Input/Output program and in this program I want the user to provide 3 different inputs and be saved in 3 different variables, they are two int and one char. 我是Java的新手,我写了一个基本的输入/输出程序,在该程序中,我希望用户提供3种不同的输入并保存在3种不同的变量中,它们是两个int和一个char。
public static void ForTesting() {
Scanner newScanTest = new Scanner(System.in);
ٍٍٍٍٍٍٍٍٍٍٍSystem.out.print("Please type two numbers: ");
int numberOne = newScanTest.nextInt();
int numberTwo = newScanTest.nextInt();
System.out.println("First Nr.: " + numberOne + " Second Nr.: " + numberTwo);
}
In the consol 在安慰
What I get: 我得到的是:
Please type two number: 4
请输入两个数字: 4
5
5
First Nr.: 4 Second Nr.: 5 第一名:4第二名:5
What I want: 我想要的是:
Please type two number: 4 5
请输入两个数字: 4 5
First Nr.: 4 Second Nr.: 5 第一名:4第二名:5
(The bold numbers are the user input) (粗体数字是用户输入的)
nextLine()
, as the name suggests, reads a single line. 顾名思义,
nextLine()
读取一行。 If both numbers are contained on this single line, you should read both integers from that line. 如果这两个数字都包含在该行中,则应该从该行中读取两个整数。 For example:
例如:
Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine(); // reads the single input line from the console
String[] strings = line.split(" "); // splits the string wherever a space character is encountered, returns the result as a String[]
int first = Integer.parseInt(strings[0]);
int second = Integer.parseInt(strings[1]);
System.out.println("First number = " + first + ", second number = " + second + ".");
Note, this will fail if you don't provide 2 integers in the input. 请注意,如果您在输入中未提供2个整数,则此操作将失败。
Please try the bellow code, i try to convert integers to strings. 请尝试以下代码,我尝试将整数转换为字符串。
public static void ForTesting() {
Scanner newScanTest = new Scanner(System.in);
ٍٍٍٍٍٍٍٍٍٍٍSystem.out.print("Please type two numbers: ");
int number = newScanTest.nextInt();
int firstDigit = Integer.parseInt(Integer.toString(number).substring(0, 1));
int secondDigit = Integer.parseInt(Integer.toString(number).substring(1, 2));
System.out.println("First Nr.: " + firstDigit + " Second Nr.: " + secondDigit);
}
If you are very sure about input like (2+2) or (2-2) or (2*2) or (2/2) below should work - 如果您非常确定以下(2 + 2)或(2-2)或(2 * 2)或(2/2)之类的输入应该可以工作-
Scanner scanner = new Scanner(System.in);
Integer first = scanner.nextInt();
String operator = scanner.next();
Integer second = scanner.nextInt();
System.out.println("First number = " + first + ", second number = " + second + ".");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.