我以为我已经有一段时间了,但后来我遇到了无限打印结果行的问题。现在我根本无法让它工作。有没有人知道如何将这种代码风格转化为符合我既定目标的功能?
import java.util.Scanner;
public class Numerical
{
public static void main (String [ ] args )
{
Scanner scan = new Scanner (System.in);
System.out.println("Please enter 5 numbers one after another");
{
int a = scan.nextInt ( ); // First number input by user
int b = scan.nextInt ( ); // Second number input by user
int c = scan.nextInt ( ); // Third number input by user
int d = scan.nextInt ( ); // Fourth number input by user
int e = scan.nextInt ( ); // Fifth number input by user
// Check if a is the greatest number
if (a > b);
while(a > c);
while(a > d);
while(a > e);
System.out.println ("The highest number is " +a);
// Check if b is the greatest number
else if (b > a);
while(b > c);
while(b > d);
while(b > e);
System.out.println ("The highest number is " +b);
// Check if c is the greatest number
else if(c > a);
while(c > b);
while(c > d);
while(c > e);
System.out.println ("The highest number is " +c);
// Check if d is the greatest number
else if(d > a);
while(d > b);
while(d > c);
while(d > e);
System.out.println ("The highest number is " +d);
// Check if e is the greatest number
else if(e > a);
while(e > b);
while(e > c);
while(e > d);
System.out.println ("The highest number is " +e);
}
}
}
答案 0 :(得分:1)
无需做所有这些。读取数组 * 的输入,使用Arrays#sort
,第一个元素是最小的,最后一个是更大的。
我不理解您的代码,那些while
和if
语句是什么?我建议你通过一个基础教程来更好地理解工作原理。如果你发现自己陷入困境,那么没有比调试代码更好的了,不仅你会发现问题,而且你会理解你为什么会这么做。
*如果您不知道输入的长度,可能需要使用ArrayList
答案 1 :(得分:0)
使用数组的好处!它们使您的代码更短,更易变,并且它们具有许多有用的功能。
import java.util.Arrays;
import java.util.Scanner;
public class Numerical {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter 5 numbers one after another");
int[] inputs = new int[5];
for (int i = 0; i < inputs.length; i++) {
inputs[i] = scan.nextInt();
}
Arrays.sort(inputs);
System.out.println("The highest number is " + inputs[inputs.length - 1]);
}
}
答案 2 :(得分:0)
最好的方法是使用数组并实现排序方法;但是,这个例子对你来说更容易理解。我们只是将每个数字与用户输入的当前最大数字进行比较:
import java.util.Scanner;
public class Blahh
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int largest = 0;
int a = scan.nextInt(); // First number input by user
int b = scan.nextInt();
largest = largest(a, b);
int c = scan.nextInt();
largest = largest(largest, c);
int d = scan.nextInt();
largest = largest(largest, d);
int e = scan.nextInt();
System.out.println("The largest number is: " + largest(largest, e));
}
public static int largest(int num1, int num2)
{
if (num1 > num2)
return num1;
else
return num2;
}
}