We help IT Professionals succeed at work.

Find largest and smallest number without array

peter_chong
peter_chong asked
on
1,139 Views
Last Modified: 2012-05-07
I would like to implement a program like follows:

Prompt the user to enter a bunch of numbers till a sentinel is enter.
Only output the max and min once the sentinel is enter.

What sentinel should I use, if all numbers entered are +ve and -ve integer.

public class MinMax{

public void main(String args[]){

int counter=0;

while(true){
    int firstNum;
    int num = readInt("Enter number:");
    if(counter==0){ firstNum=num;}
    counter++;
    max=min=firstnum;
    if(num==SENTINEL){
     if(num<min) println("Min:"+min)  ;
     if(num<max) println("Max:"+min)  ;
     break;  
    }//end if
}//end while
   
}//end main

}//end class
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2016

Commented:
You haven't defined min/max

int max = Integer.MIN_VALUE;
max = Math.max(max, num);
int max = Integer.MIN_VALUE; // (before loop)
...
max = Math.max(max, num);

Open in new window

a_b
Top Expert 2009

Commented:
Can you ask the user how many number he wants to enter and then take as input that many numbers? Otherwise you might have to do some extra processing to get the numbers.

Author

Commented:
To CEHJ,
Actually, this is an exercise that I try to sharpen my programming skill without using much reusable library and preferably write by my own functions.

To a_b,
Can you ask the user how many number he wants to enter and then take as input that many numbers?
Can not in this case.
Since this is an exercise that I try to sharpen my programming skill without using much reusable library and preferably write by my own functions.

Sorry Guys. :-)


CERTIFIED EXPERT
Top Expert 2016

Commented:
>>
Actually, this is an exercise that I try to sharpen my programming skill without using much reusable library and preferably write by my own functions.
>>

Well there's very little difference actually in doing what i suggested and doing the below, but either way, you need to define the variable:
if (max < num) {
    max = num;
}

Open in new window

Author

Commented:
Hi CEHJ,
How about the integer sentinel, if I allow all integers to be enter?

Any other alternative? (refer my code above)

thanks.
CERTIFIED EXPERT
Top Expert 2016
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
CEHJ:
Yes, you are right.

I honors 250 marks to you.
CERTIFIED EXPERT
Top Expert 2016

Commented:
:-)
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.