Getting the lowest and highest value from integers without using arrays?

前端 未结 2 943
不知归路
不知归路 2020-12-12 06:13

I\'m trying to write a class which reads 5 integers from the user and returns the highest and lowest value back. This must be done using loops and without using arrays and I

相关标签:
2条回答
  • 2020-12-12 06:58

    Why not just repeat your max logic for min?

    public class Ovning_321 {
        public static void main(String[] args){
    
            Scanner input = new Scanner(System.in);
            System.out.print("Give me an integer: "); 
    
            number = input.nextInt();
            int max = number;
            int min = number;
    
                  for (int x = 0; x<4; x++){ 
                        System.out.print("Give me an integer: "); 
                        number = input.nextInt(); 
    
                        if (number > max){ 
                            max = number;  
                        }
    
                        if (number < min){ 
                            min = number;  
                        } 
                  }                 
                  System.out.println("Highest value: " + max);
                  System.out.println("Lowest value: " + min);
            }
     }
    

    Note that max and min are initially set to the first number that the user enters, so there will be no false 0's and no need to MAX_INT or MIN_INT. This in turn makes the loop run once less so terminate at i == 4 instead of 5.

    0 讨论(0)
  • 2020-12-12 07:14

    here you go :)

    import java.util.Scanner;
    
        public class Ovning_321 {
            public static void main(String[] args){
                Scanner input = new Scanner(System.in);
                int number;
                int max = 0;
                int min = 0;
    
                      for (int x = 0; x<5; x++){ 
                            System.out.print("Give me an integer: "); 
                            number = input.nextInt(); 
    
                            if (x == 0 || number > max){ 
                                max = number;  
                            }               
                            if (x == 0 || number < min){ 
                                min = number;  
                            }               
                      }                 
                      System.out.println("Highest value: " + max);
                      System.out.println("Lowest value: " + min);
                }
         }
    
    0 讨论(0)
提交回复
热议问题