-2

我正在为 12 年级的学校课程做一些基本的 Java 工作,并且正在努力找出我在这段代码中的错误。当 num2 大于 num1 时,输出很好,但是当 num1 大于 num2 时,我得到 3 个输出而不是 2 个。我不确定我是否在括号上做错了,但我才刚刚开始学习 java 并且看不到这个问题。

例如,如果 num1 是 3,而 num2 是 2,我得到 2 , 3 , 2 作为我的输出,但是如果 num1 是 2 并且 num2 是 3,我得到 2,3 作为我的输出

import java.util.*;

public class HigherNumber
{
    public static void main (String[] args)
    {
        int num1 = 0;
        int num2 = 0;
        Scanner scannum1 = new Scanner (System.in);
        Scanner scannum2 = new Scanner (System.in);

        System.out.print("Enter your first number: ");
        num1 = scannum1.nextInt();
        scannum1.close();

        System.out.print("Enter your second number: ");
        num2 = scannum2.nextInt();
        scannum2.close();

        {
        if (num1 > num2) {
            System.out.println (num2);
            System.out.println (num1);
        }
        else
            System.out.println (num1);
            System.out.println (num2);
        }
    }
}
4

2 回答 2

4
else      
 System.out.println (num1);
 System.out.println (num2);

需要一个大括号:

else {    
    System.out.println (num1);
    System.out.println (num2);
}

整个代码(因为你到处都失去了大括号)应该是:

import java.util.*;

public class HigherNumber{
    public static void main (String[] args){
        int num1 = 0;
        int num2 = 0;
        Scanner scannum1 = new Scanner (System.in);
        Scanner scannum2 = new Scanner (System.in);
        System.out.print("Enter your first number: ");
        num1 = scannum1.nextInt();
        scannum1.close();
        System.out.print("Enter your second number: ");
        num2 = scannum2.nextInt();
        scannum2.close();
        if (num1 > num2) {
            System.out.println (num2);
        System.out.println (num1);
        }
        else{    
            System.out.println (num1);
            System.out.println (num2);
        }
    }
}
于 2013-07-29T01:37:42.967 回答
0

无需创建两个不同的 Scanner - 您可以创建一个 Scanner 实例并调用 nextInt() 两次不同的时间。像这样:

Scanner scannum1 = new Scanner (System.in);
System.out.print("Enter your first number: ");
num1 = scannum1.nextInt();
System.out.print("Enter your second number: ");
num2 = scannum1.nextInt();
scannum1.close();
于 2013-07-29T01:44:28.793 回答