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

前端 未结 2 944
不知归路
不知归路 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.

提交回复
热议问题