Java:扫描输入时使用空格或输入作为分隔符时的不同输出

Java: different output when scanning input with spaces or enters as delimiters

我正在尝试从用户那里获取输入并使用 Java 8(IDE BlueJ,Windows 10)将其打印到控制台。 打印输出时有一个错误:程序打印方程式 2 两次,而不是打印方程式 1 和方程式 2。

这是代码:

import java.util.Scanner;

public class Equations
{
        public static void main (String[] args)

    {
        Scanner scan = new Scanner (System.in); 

        System.out.println("This program solves a system of 2 linear equations");
        System.out.println("Enter the coefficients a11 a12 a21 a22 b1 b2");

        int a11 = scan.nextInt();
        int a12 = scan.nextInt();
        int a21 = scan.nextInt();
        int a22 = scan.nextInt();
        int b1 = scan.nextInt();
        int b2 = scan.nextInt();

        System.out.println("Eq1: "+ a11 +"*x1+"+ a12 +"*x2="+ b1);
        System.out.println("Eq2: "+ a21 +"*x1+"+ a22 +"*x2="+ b2);

    }
}

这是预期的输出:

This program solves a system of 2 linear equations Enter the coefficients a11 a12 a21 a22 b1 b2
1 2 3 4 5 6
Eq1: 1*x1+2*x2=5
Eq2: 3*x1+4*x2=6

这是输出:

This program solves a system of 2 linear equations Enter the coefficients a11 a12 a21 a22 b1 b2
1 2 3 4 5 6
Eq2: 3*x1+4*x2=6
Eq2: 3*x1+4*x2=6

请注意,仅当在数字之间有空格的单行输入时存在此错误,在每个数字后按 Enter 键时不存在此错误。

意思是,如果一次输入一个数字,就会正确收到预期的输出:

This program solves a system of 2 linear equations Enter the coefficients a11 a12 a21 a22 b1 b2

1

2

3

4

5

6

Eq1: 1*x1+2*x2=5
Eq2: 3*x1+4*x2=6

由于难以置信且难以重现,这里是屏幕截图:

当输入以空格分隔的单行与以输入分隔的不同行时,造成差异的原因是什么?

当输入为单行格式时如何获得所需的输出?

您的 IDE 看起来像是一个错误。考虑以下因素:

import java.util.Scanner;

public class Equations
{
    public static void main (String[] args) {

        Scanner scan = new Scanner("1 2 3 4 5 6");

        System.out.println("This program solves a system of 2 linear equations");
        System.out.println("Enter the coefficients a11 a12 a21 a22 b1 b2");

        int a11 = scan.nextInt();
        int a12 = scan.nextInt();
        int a21 = scan.nextInt();
        int a22 = scan.nextInt();
        int b1 = scan.nextInt();
        int b2 = scan.nextInt();

        System.out.println("Eq1: "+ a11 +"*x1+"+ a12 +"*x2="+ b1);
        System.out.println("Eq2: "+ a21 +"*x1+"+ a22 +"*x2="+ b2);

    }
}

它是完全相同的代码,只是它不依赖于用户输入。输入以空格分隔,输出为预期:

This program solves a system of 2 linear equations
Enter the coefficients a11 a12 a21 a22 b1 b2
Eq1: 1*x1+2*x2=5
Eq2: 3*x1+4*x2=6

online Java compiler

尝试明确设置分隔符:

scan = new Scanner(System.in).useDelimiter(" |\n");