基本Java,最大和最小整数

时间:2018-10-04 16:34:19

标签: java

该代码的目的是提示用户输入10个整数,然后显示最大和最小的整数。我能够要求用户输入10个整数并显示最大的数字。但是,没有显示最小的数字。我认为问题出在我将最小设置为0。

import java.util.Scanner;

public class LargeSmall {
 public static void main(String[] args) {

 int counter = 1;
 int largest = 0; 
 int smallest = 0;
 int number = 0;  

 Scanner input= new Scanner(System.in);

 while (counter <= 10) {
     System.out.print("Enter number: ");
     number = input.nextInt();
     if (number > largest) {
         largest = number;
     }else if(number < smallest) {
         smallest = number;  
     }else {
         System.out.print("Number isn't distinct");   
         counter = counter + 1;
     }  

     System.out.println("Largest number is: " + largest);
     System.out.println("Smallest number is: " + smallest);
  }
}

4 个答案:

答案 0 :(得分:2)

以这种方式初始化您的值,因此我们保证我们从与数字进行比较的最小/最大参考开始:

int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
int number;
int old = Integer.MIN_VALUE;

...然后必须进行一些调整:

  • 更改检查重复编号的方式(use和old变量)。
  • 检查每个新数字是否总是小于smallest个数字(因此,在第一次迭代中,我们将第一个值分配给smallestlargest

像这样:

 number = input.nextInt();
 if (old != number) {
     old = number;
     if (number > largest) {
         largest = number;
     } 
     if(number < smallest) {
         smallest = number;  
     }
    /* consider moving next line here (this will guarantee to go to the next
       iteration only if the numbers are different, and get in the final messages,
       valid values for `smallest` and `largest` */
    // counter = counter + 1;
 } else {
      System.out.print("Number isn't distinct");
 }

答案 1 :(得分:1)

只需将>变成>=,然后将<变成`<=

由于0 < 0的值为false,因此您的代码块无法运行。这样更正。

答案 2 :(得分:0)

变量smallest始终为0,因此程序永远不会进入此块else if(number < smallest) 您应该在if(number < smallest)

之前添加此代码
    if(smallest == 0) {
         smallest = number;
    }

您的代码也不会捕获不同的数字。要查找不同的数字,您应该在程序开始时定义一个列表List<Integer> numbers = null;

然后您可以像这样检查在while循环中是否输入了输入:

   if(numbers.contains(number))
        System.out.print("Number isn't distinct");
    else 
        numbers.add(number);

答案 3 :(得分:0)

使用用户的第一个输入设置最大和较小的变量,然后进行比较

import java.util.Scanner;

public class LargeSmall {
    public static void main(String[] args) {

        System.out.print("Enter number: ");
        Scanner input= new Scanner(System.in);
        int number = input.nextInt();
        int counter = 1;
        int largest = number; 
        int smallest = number;


        while (counter < 10) {
           System.out.print("Enter number: ");
           number = input.nextInt();
           if (number > largest) {
               largest = number;
           }else if(number < smallest) {
               smallest = number;  
           }else 
               System.out.print("Number isn't distinct");   

           counter = counter + 1;
       }  

       System.out.println("Largest number is: " + largest);
       System.out.println("Smallest number is: " + smallest);
    }
}