5.2 Write a program that repeatedly prompts
a user for integer numbers until the user
enters 'done'. Once 'done' is entered, print out
the largest and smallest of the numbers. If
the user enters anything other than a valid
number catch it with a try/except and put out
an appropriate message and ignore the
number. Enter 7, 2, bob, 10, and 4 and match
the output below.
Answers
Answer:
import java.util.Scanner;
import java.util.*;
public class Main
{
public static void main (String[]args)
{
List < Integer > integers = new ArrayList < Integer > ();
Scanner in = new Scanner (System.in);
String input;
while (true)
{
try
{
System.out.println ("Enter number or Type done");
input = in.next ();
if (input.equals("done"))
{
ShowMinandMax (integers);
break;
}
else
{
integers.add (Integer.parseInt (input));
}
}
catch (Exception ex)
{
System.out.println ("Please enter proper Integer");
}
}
}
public static void ShowMinandMax (List < Integer > integers)
{
System.out.println ("_---------------Max-------------------_");
System.out.println (Collections.max (integers));
System.out.println ("_---------------Min-------------------_");
System.out.println (Collections.min (integers));
}
}
Explanation:
Answer:
largest=None
smallest=None
while True:
num = raw_input("Enter a number: ")
if num=="done":break
try:
num=int(num)
if largest is None or num>largest: largest=num
if smallest is None or num<smallest: smallest=num
except:
print("Invalid input")
continue
print("Maximum is", largest)
print("Minimum is",smallest)
Explanation:
learning from py4e.com