SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Conditional Execution
Exercise:
Exercises
Question:6 | ISBN:9780136091813 | Edition: 2

Question

Write a method called smallestLargest that accepts a Scanner for the console as a parameter and asks the user to enter numbers, then prints the smallest and largest of all the numbers supplied by the user. You may assume that the user enters a valid number greater than 0 for the number of numbers to read. Here is a sample execution:

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

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program:

import java.util.Scanner;
public class Ch04Ex06
{
	public static void main(String[] args)
	{
		Scanner keyboard = new Scanner(System.in);
		
		smallestLargest(keyboard);
	}

	public static void smallestLargest(Scanner keyboard)
	{
		int n;		
		int number;
		int smallest = 0;
		int largest = 0;
		
		System.out.print("How many numbers do you want to enter? ");
		n = keyboard.nextInt();	

		for (int i = 1; i <= n; i++)
		{
			System.out.print("Number " + i + ": ");
			number = keyboard.nextInt();
			
			if(i == 1)
			{
				smallest = number;
				largest = number;
			}
			else if (number < smallest)
			{
				smallest = number;
			}			
			else if (number > largest)
			{
				largest = number;
			}
		}

		System.out.println("Smallest = " + smallest);
		System.out.println("Largest = " + largest);
	}
}

Output:

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

 

0 0

Discussions

Post the discussion to improve the above solution.