如何修改此代码以按顺序打印3个整数?

时间:2015-11-18 14:16:17

标签: java

我有一个代码打印3个整数之间的最大整数,我想对这3个整数进行排序(如num < num1 < num2)。

我想修改我的代码来实现这一目标,我该怎么做?

import java.util.Scanner;
public class digits
{
    public static void main(String[] args)
    {
        int num = 0;
        int num1 = 0;
        int num2 = 0;
        int big = 0;
        System.out.println("Please insert 3 numbers: ");
        Scanner number = new Scanner (System.in);

        if (number.hasNextInt())
        {
            num = number.nextInt();
            big=num;
        }

        if (number.hasNextInt())
        {
            num1 = number.nextInt();
            if(num1>num)
            {
                big=num1;
            }
        }

        if (number.hasNextInt())
        {
            num2 = number.nextInt();

            if(num2>num && num2>num1)
            {
                big=num2;
            }

            System.out.println(big+ ">" +num1+ ">" +num);
        }
        else
        {
            System.out.println("Error: Invalid Value.");
        }
    }
}

4 个答案:

答案 0 :(得分:1)

尝试以下代码

City

答案 1 :(得分:0)

看看你的代码:你选择三个数字中最大的一个(大),但你永远不会改变num1或num。 因此,您的结果将始终为:距number>second value的{​​{1}}更高System.in>third value

换句话说,您只对较高的值进行排序。

答案 2 :(得分:0)

if(num1>num)
{
    big=num1;
}

将其更改为:

if(num1>num)
{
    big=num1;
}
else
{
    // swap num1 and num
    int tmp = num;
    num = num1;
    num1 = num;
}

同时更改

if(num2>num && num2>num1)
{
    big=num2;
}

if(num2>num1)
{
    big=num2;
}
else
{
    // num1 is largest, so swap num1 and num2
    int tmp = num1;
    num1 = num2;
    num2 = tmp;
    if(num > num1){
        //swap num and num1
        int t = num1;
        num1 = num;
        num = t;
    }
 }

答案 3 :(得分:0)

这样的事情应该有效

import java.util.Scanner; 
public class digits {

public static void main(String[] args)
{
    int[] nums = new int[3];
    int k = 0;
    System.out.println("Please insert 3 numbers: ");
    Scanner number = new Scanner (System.in);

    while (number.hasNext() && k < 3) {
        int i = 0;
        try {
            i = Integer.parseInt(number.nextLine());
        }
        catch (NumberFormatException e) {
            System.out.println("Error: Invalid Value.");
        }
        nums[k] = i;
        k++;
    }
    Arrays.sort(nums);
    System.out.println(nums[2]+ ">" +nums[1]+ ">" +nums[0]);

  }
}