【问题标题】:Find maximum of three inputs查找最多三个输入
【发布时间】:2018-02-25 02:14:08
【问题描述】:

以下是我们需要采取的步骤:


一个。使用 Scanner 类创建一个对象以从键盘读取输入。

b.声明三个 int 变量,分别称为 x、y、z 和 max。

c。提示用户输入变量 x、y 和 z 的值。

d。求 x、y 和 z 的最大值,然后将最大值赋给 max。

e。显示最大值。

我的代码似乎无休止地运行这是我的代码有什么问题:

import java.util.Scanner;

public class Maximum {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        int x;
        int y;
        int z;
        int max;

        System.out.print("Enter Value For x: ");
        x = keyboard.nextInt();

        System.out.print("Enter Value For y: ");
        y = keyboard.nextInt();

        System.out.print("Enter Value For z");
        z = keyboard.nextInt();

        max = Math.max(Math.max(x, y), z);

        if (x > y && x > z) {
            x = max;
        }
        if (y > x && y > z) {
            y = max;
        }
        if (z > x && z > y) {
            z = max; // Getting "assigned value is never used"
        }
        System.out.println("The Maximum is" + max);
    }
}

【问题讨论】:

  • 为什么要将max 分配回xyz?那是在哪里指定的,你在哪里使用它?你是怎么运行这个的?

标签: java if-statement logic java.util.scanner


【解决方案1】:

我刚刚运行了您的代码,据我所知没有问题。它运行良好。即使我删除了您的 if 语句,它也运行良好(因为真正的最大确定是由分配 int max 的代码完成的。

我把整个事情压缩成这样:

Scanner scan = new Scanner(System.in);

System.out.print("Enter Value For x: ");
int x = scan.nextInt();

System.out.print("Enter Value For y: ");
int y = scan.nextInt();

System.out.print("Enter Value For z: ");
int z = scan.nextInt();

int max = Math.max(Math.max(x, y), z);
System.out.println("The Maximum is " + max);

然后输出

Enter Value For x: 5
Enter Value For y: 10
Enter Value For z: 15
The Maximum is 15

Process finished with exit code 0

【讨论】:

    【解决方案2】:

    嗯,我稍微修改了你的程序。我在创建扫描仪对象之前声明了变量,它工作得很好。这是你的代码:

    import java.util.Scanner;
    
    public class Maximum {
    public static void main(String[] args)
    {
    int x;
    int y;
    int z;
    int max;
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter Value For x: ");
    x = keyboard.nextInt();
    
    System.out.print("Enter Value For y: ");
    y = keyboard.nextInt();
    
    System.out.print("Enter Value For z: ");
    z = keyboard.nextInt();
    
    max = Math.max(Math.max(x, y), z);
    
    if (x > y && x > z)
    {
        x = max;
    }
    if (y > x && y > z)
    {
        y = max;
    }
    if (z > x && z > y)
    {
        z = max;  // Getting "assigned value is never used"
    }
    System.out.println("The Maximum is: " + max);
    }
    

    }

    样本输出:

    Enter Value For x: 6
    Enter Value For y: 7
    Enter Value For z: 5
    The Maximum is: 7
    

    【讨论】:

      猜你喜欢
      • 2014-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-05
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多