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

我正在尝试从用户那里获取输入并使用 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);


    }

}

这是预期的输出:


该程序求解 2 个线性方程组 输入系数 a11 a12 a21 a22 b1 b2

1 2 3 4 5 6

Eq1: 1*x1+2*x2=5

Eq2: 3*x1+4*x2=6


这是输出:


该程序求解 2 个线性方程组 输入系数 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 键时不存在。


意思是,如果输入一次出现一个数字,则正确接收预期的输出:


该程序求解 2 个线性方程组 输入系数 a11 a12 a21 a22 b1 b2


1


2


3


4


5


6


等式 1:1*x1+2*x2=5 等式 2

:3*x1+4*x2=6


由于难以相信且难以重现,这里有一个屏幕截图:

http://img3.mukewang.com/62e12a38000113c619191084.jpg

当输入出现在单行中,由空格分隔时,与输入出现在单独的行中,由输入分隔时,是什么导致了差异?

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


慕斯王
浏览 257回答 1
1回答

慕仙森

看起来像您的 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 equationsEnter the coefficients a11 a12 a21 a22 b1 b2Eq1: 1*x1+2*x2=5Eq2: 3*x1+4*x2=6请参阅在线 Java 编译器尝试明确设置分隔符:scan = new Scanner(System.in).useDelimiter(" |\n");
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java