Min Value and Print User input

chris0044
chris0044 used Ask the Experts™
on
Hi,

I' m student and I'm having trouble printing out the minimum value and also to print out what the user inputs. Could someone tell me what I'm doing wrong?

public static void main(String args[]){
		
	int numbers;
	int inputData = 0;
	int largest = 0;
	int smallest = inputData;
	Scanner scan = new Scanner(System.in);
	
		System.out.print("How many numbers do you want to enter?");
		numbers = scan.nextInt();
		
		for (int index = 1; index <= numbers; index ++){
		System.out.print("Number " + index + ": ");
		inputData = scan.nextInt();
		if (inputData > largest){
			largest = inputData;
			if (inputData < smallest){
				smallest =inputData;
			}
		  }
		}
		
		System.out.println ("largest Value is " + largest);
		System.out.println ("smallest Value is " + smallest);
		
		System.out.println("You've entered: ");
		for (int index = 1; index <= numbers; index ++){
			System.out.print(inputData + " ");
		}
		
} 
} 

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Your problem is here:

if (inputData > largest){
                  largest = inputData;
                  if (inputData < smallest){
                        smallest =inputData;
                  }
              }
            }

You don't want the second "if" to be inside the first "if".

So make it:
if (inputData > largest){
                  largest = inputData;
}

if (inputData < smallest){
                  smallest =inputData;
}

This is also not going to do what you expect:

for (int index = 1; index <= numbers; index ++){
                  System.out.print(inputData + " ");
            }

It just prints out the last number multiple times.  You should look at either storing each input value in an array or building up a string as you go and then printing out the string.

Doug

Author

Commented:
I havechanged the if statements but the smallest values still doesn't give me the right answer. I have also changed int smallest = inputData; to int smallest = 0; but it doesn't work.
Oh yes that's another bug.  You should initialize smallest to something really big - e.g.

int smallest = Integer.MAX_VALUE ;

Otherwise all of the values you are testing will be larger than the "0" that you started with and you will always end up with "smallest = 0" at the end.

Doug

Author

Commented:
Thanks, it works now

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial