【问题标题】:Displaying the lowest and higher number in Java after User Input?用户输入后在Java中显示最小和更高的数字?
【发布时间】:2013-11-13 03:28:38
【问题描述】:

如何在Java中显示最小和最大的数字?我知道我需要使用这个变量: int max = Integer.MIN_VALUE; int min = Integer.MIN_VALUE;但我无法让它工作。 :/ 有什么帮助吗?

导入 java.util.Scanner;

public class LoopingNumbersUsingWhile {
public static void main(String args[]) {
    Scanner kb = new Scanner(System.in);

    System.out.println("How Many Numbers You Want To Enter: ");
    int total = kb.nextInt();
    int input = 0;
    int sum = 0;
    int average=0;
    int max = Integer.MIN_VALUE;
    int min = Integer.MIN_VALUE;
    while (input < total) {
        input++;

        System.out.println("Enter " + input + ". Operand: ");

                    sum += kb.nextInt();

   if (min >= sum) 
  { 
    min = sum;
  } 
if (max <= sum) 
  { 
  max = sum;
  } 



       average = ( sum ) / ( input);
    }
    System.out.println("The sum is " + sum + ".");
    System.out.println("The avg  " + average);
    System.out.println("The higher number  " + max);
    System.out.println("The the lowest number " + min);


   }
  }

【问题讨论】:

  • 基本上对于最小值和最大值,您与错误的数字进行比较sum
  • 感谢您的帮助!但我还没有想通。我已经尝试了所有我能想到的想法。任何其他建议将不胜感激。谢谢

标签: java


【解决方案1】:

您需要将下一个数字读入一个临时变量,然后将其添加到 sum。

int temp = kb.nextInt();
sum+=temp

并针对您的临时变量进行这些检查。

if (min >= temp) 
{ 
 min = temp;
} 
if (max <= temp) 
{ 
max = temp;
} 

【讨论】:

  • 还有int min = Integer.MIN_VALUE;需要改成int min = Integer.MAX_VALUE;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-28
  • 1970-01-01
  • 2016-07-24
  • 1970-01-01
  • 2017-12-11
  • 2016-08-08
  • 2014-08-03
相关资源
最近更新 更多