In: Computer Science
Write a complete java program that Define a class named sample containing:
Please enter two numbers to divide: 10 Hi
You entered wrong input. Try again.
Please enter two numbers to divide: 15 0
Division could not be completed.
Enter 5 double numbers: 2.5 3.1 5.0 9.3 10.0
Which element you want to print? (Choose a number between 0-4): 7
Wrong choice. Try again.
Which element you want to print? (Choose a number between 0-4): 3
The element in position 3 = 9.3
Thank you for using this program.
Sample.java
import java.util.Scanner;
//Write a complete java program that Define a class named sample
containing:
public class Sample
{
//A method named division that
//receives two integers x and y and returns the
division of the two numbers.
double division(double a, double b)
{
//denominator cannot be 0
if(b==0)
{
System.out.println("Division could not be completed");
return
0.0;
}
double result = a/b;
//It must handle any possible exceptions.
return result;
}
//A method named printArray that receives an array of
double arr and an integer index and prints the element in the
positon index.
double printArray(double arr[], int index)
{
double result = 0.0;
if(index < 0 || index >
4)
{
throw new
NumberFormatException();
}
result = arr[index];
//It must handle any possible
exceptions.
return result;
}
//main method that recievs input from user and repeat
if wrong input. Then it should call the other methods.
public static void main(String args[])
{
Scanner sc = new
Scanner(System.in);
Sample s = new Sample();
while(true)
{
System.out.println("Please enter two numbers to divide");
String first =
sc.next();
String second =
sc.next();
try
{
double num1 = Double.parseDouble(first);
double num2 = Double.parseDouble(second);
double result = s.division(num1, num2);
if(num1 != 0.0 && result == 0.0)
{
}
else
{
System.out.println("Division
of "+num1+" by "+num2+" is "+result);
}
break; // this line will come if both num1 and
num2 are valid numbers
}
catch
(NumberFormatException nfe)
{
System.out.println("You entered wrong input. Try again");
}
}
while(true)
{
System.out.println("Enter 5 double numbers:");
String first =
sc.next();
String second =
sc.next();
String third =
sc.next();
String fourth =
sc.next();
String fifth =
sc.next();
try
{
double arr[] = new double[5];
arr[0] = Double.parseDouble(first);
arr[1] = Double.parseDouble(second);
arr[2] = Double.parseDouble(third);
arr[3] = Double.parseDouble(fourth);
arr[4] = Double.parseDouble(fifth);
System.out.println("Which element you want to
print? (Choose a number between 0-4): ");
String option = sc.next();
int i = Integer.parseInt(option);
double result = s.printArray(arr, i);
System.out.println("The element in position
"+i+" = "+result);
break; // this line will come if all numbers in
array are valid numbers
}
catch
(NumberFormatException nfe)
{
System.out.println("Wrong choice. Try again");
}
}
System.out.println("Thank you for
using this program");
sc.close();
}
}
Sample I/O and output