为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕斯王 2022-07-27 20:05:54
我正在尝试从用户那里获取输入并使用 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 b21 2 3 4 5 6Eq1: 1*x1+2*x2=5Eq2: 3*x1+4*x2=6这是输出:该程序求解 2 个线性方程组 输入系数 a11 a12 a21 a22 b1 b21 2 3 4 5 6Eq2: 3*x1+4*x2=6Eq2: 3*x1+4*x2=6请注意,该错误仅在数字之间带有空格的单行输入时存在,并且在每个数字后按 Enter 键时不存在。意思是,如果输入一次出现一个数字,则正确接收预期的输出:该程序求解 2 个线性方程组 输入系数 a11 a12 a21 a22 b1 b2123456等式 1:1*x1+2*x2=5 等式 2:3*x1+4*x2=6由于难以相信且难以重现,这里有一个屏幕截图:当输入出现在单行中,由空格分隔时,与输入出现在单独的行中,由输入分隔时,是什么导致了差异?当输入为单行格式时,如何获得所需的输出?
查看完整描述

1 回答

?
慕仙森

TA贡献1827条经验 获得超8个赞

看起来像您的 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

请参阅在线 Java 编译器


尝试明确设置分隔符:


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


查看完整回答
反对 回复 2022-07-27
  • 1 回答
  • 0 关注
  • 189 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号