Reputation: 11
Write a method named smallestLargest that asks the user to enter numbers, then prints the smallest and largest of all the numbers typed in by the user. You may assume the user enters a valid number greater than 0 for the number of numbers to read. Here is an example dialogue:
How many numbers do you want to enter? 4
Number 1: 5
Number 2: 11
Number 3: -2
Number 4: 3
Smallest = -2
Largest = 11
This is what i have done but i am unable to get the smallest and largest output.
import java.util.*;
public class smallestLargest{
public static void main(String[] args){
System.out.print("How many numbers do you want to enter? ");
Scanner sc=new Scanner(System.in);
int count=sc.nextInt();
int smallest=Integer.MAX_VALUE;
int largest=Integer.MIN_VALUE;
for(int i=1;i<=count;i++){
System.out.println("Number" + i + ": ");
int nextNumber=sc.nextInt();
if(nextNumber<smallest){
smallest+=nextNumber;
}
else if(nextNumber<largest){
largest+=nextNumber;
}
}
System.out.println("Smallest= "+ smallest);
System.out.println("Largest= "+ largest);
}
}
Upvotes: 0
Views: 8783
Reputation: 1753
Little bit 'I am lazy' solution:
Scanner sc = new Scanner(System.in);
List<Integer> numbers = new ArrayList<Integer>();
while (sc.hasNextInt())
{
numbers.add(sc.nextInt());
}
System.out.println("Smallest= " + Collections.min(numbers));
System.out.println("Largest= " + Collections.max(numbers));
Upvotes: 0
Reputation: 1
Don't use "else if", because on the first loop, the number will pass both tests - i.e. it will be the smallest AND the largest, also don't use "+=", just "=" and change the "largest". So something like:
if(nextNumber<smallest)
smallest=nextNumber;
if(nextNumber>largest)
largest=nextNumber;
Upvotes: 0
Reputation: 1500385
This is the problem:
if(nextNumber<smallest){
smallest+=nextNumber;
}
else if(nextNumber<largest){
largest+=nextNumber;
}
That doesn't do what you want at all.
I'm not going to give you the solution, but think about it - just do one of them at a time. Let's start with "smallest".
If our current smallest number is 5, and someone enters 2, what should the new smallest number be? Why?
If our current smallest number is 5, and someone enters 10, what should the new smallest number be? Why?
Work that out, then apply the same thought process to "largest number".
Upvotes: 2