有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java:如何在控制台的一行中有两个或多个输入

我是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

五,

第一批:4第二批:5


我想要的是:

请键入两个数字:4 5

第一批:4第二批:5

(粗体数字为用户输入)


共 (3) 个答案

  1. # 1 楼答案

    如果你对输入非常确定,比如(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 + ".");
    
  2. # 2 楼答案

    请尝试下面的代码,我尝试将整数转换为字符串

    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);
    }
    
  3. # 3 楼答案

    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个整数,则此操作将失败