我正在为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);
}
}
}
答案 0 :(得分: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);
}
}
}
答案 1 :(得分:0)
无需创建两个不同的扫描仪 - 您可以创建一个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();