我是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);
}
在安慰中
我得到的是:
请输入两个数字: 4
5
第一名:4第二名:5
我想要什么:
请输入两个数字: 4 5
第一名:4第二名:5
(粗体数字是用户输入的内容)
答案 0 :(得分:2)
nextLine()
读取一行。如果这两个数字都包含在该行中,则应该从该行中读取两个整数。例如:
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 + ".");
请注意,如果您在输入中未提供2个整数,则此操作将失败。
答案 1 :(得分:0)
请尝试以下代码,我尝试将整数转换为字符串。
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);
}
答案 2 :(得分:0)
如果您非常确定输入(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 + ".");