Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

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

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 Integer.MIN.Value/Integer.MAX.Value. I've already succeeded writing code that gets 5 integers from the user and returns the highest value but I just can't get both the highest and the lowest value returned in the same class.

Here is the code I mentioned above:

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;

            for (int x = 0; x<5; x++){ 
                 System.out.print("Give me an integer: "); 
                 number = input.nextInt(); 

                 if (number > max){ 
                      max = number;  
                 }              
             }                  
             System.out.println("Highest value: " + max);
     }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
            }
     }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...