我刚刚开始学习Java而且我正在通过一个更有效的程序来解决这个问题,但我想理解为什么两次输入相同的数字会导致程序无法一直运行通过?
我需要编写一个程序,用户输入三个数字,然后按非降序排序。
import java.util.Scanner;
public class ModThreeReorder{
public static void main(String []args){
java.util.Scanner input = new java.util.Scanner(System.in);
int num1;
int num2;
int num3;
System.out.println("Please enter three (3) numbers");
num1 = input.nextInt();
num2 = input.nextInt();
num3 = input.nextInt();
System.out.println("Thanks. You entered " + num1 + ", " + num2 + ", " + num3 + ".");
if (num1 > num2 && num1 > num3){
if (num2 > num3 || num2 == num3){
System.out.println("Your numbers in non-descending order are " + num3 + ", " + num2 + ", " + num1 + ".");
}
else if (num3 > num2 || num3 == num2){
System.out.println("Your numbers in non-descending order are " + num2 + ", " + num3 + ", " + num1 + ".");
}
}
else if (num2 > num1 && num2 > num3){
if (num1 > num3 || num1 == num3){
System.out.println("Your numbers in non-descending order are " + num3 + ", " + num1 + ", " + num2 + ".");
}
else if (num3 > num1 || num3 == num1){
System.out.println("Your numbers in non-descending order are " + num1 + ", " + num3 + ", " + num2 + ".");
}
}
else if (num3 > num1 && num3 > num2){
if (num1 > num2 || num1 == num2){
System.out.println("Your numbers in non-descending order are " + num2 + ", " + num1 + ", " + num3 + ".");
}
else if (num2 > num1 || num2 == num1){
System.out.println("Your numbers in non-descending order are " + num1 + ", " + num2 + ", " + num3 + ".");
}
}
}
}
答案 0 :(得分:0)
您必须清理缓冲区,尝试在scanner.nextLine();
之后放置nextInt()
。
此方法返回当前行的其余部分,不包括末尾的任何行分隔符。该位置设置为下一行的开头。由于此方法继续搜索输入以查找行分隔符,因此如果不存在行分隔符,它可以缓冲搜索要跳过的行的所有输入。
答案 1 :(得分:0)
如果不以某种方式清除缓冲区,则无法直接执行三次整数。这是我喜欢的友好方式
System.out.println("Please enter number one :: ");
num1 = input.nextInt();
System.out.println("Please enter number two :: ");
num2 = input.nextInt();
System.out.println("Please enter number three :: ");
num3 = input.nextInt();
这将为您提供您期望的结果。
程序中的另一个缺陷是确定哪个数字最小的逻辑。你应该有类似的东西:
if(num1 >= num2 && num1 >= num3){
if(num2 >= num3)
System.out.println(num3 +" "+ num2 + " "+ num1);
else
System.out.println(num2+" "+num3+" "+num1);
}else if(num2 >= num1 && num2 >= num3){
if(num1 >= num3)
System.out.println(num3 +" "+ num1 + " "+ num2);
else
System.out.println(num1 +" "+ num3 + " "+ num1);
}else{
if(num1 >= num2)
System.out.println(num2 +" "+ num1 + " "+ num3);
else
System.out.println(num2 +" "+ num1 + " "+ num3);
}
因此,将所有这些放在一起将允许您正确地获取三个int输入,然后按降序排序和显示它们。