Question: Java Assignment When dividing by 0, I need to suppress the Answer:Infinity that comes up. Here is my code. import java.util.Scanner; public class BasicCalculator {

Java Assignment

When dividing by 0, I need to suppress the Answer:Infinity that comes up.

Here is my code.

import java.util.Scanner;

public class BasicCalculator {

public static void main(String[] args) {

float a, b, res;

char choice, ch;

Scanner scan = new Scanner(System.in);

do

{

System.out.print("1. Add ");

System.out.print("2. Subtract ");

System.out.print("3. Multiply ");

System.out.print("4. Divide ");

System.out.print("5. Generate Random Number ");

System.out.print("What would you like to do? ");

choice = scan.next().charAt(0);

switch(choice)

{

case '1':

System.out.print("What is the first number? ");

a = scan.nextFloat();

System.out.print("What is the second number? ");

b = scan.nextFloat();

res = a + b;

System.out.print("Answer: " + res);

break;

case '2':

System.out.print("What is the first number? ");

a = scan.nextFloat();

System.out.print("What is the second number? ");

b = scan.nextFloat();

res = a - b;

System.out.print("Answer: " + res);

break;

case '3':

System.out.print("What is the first number? ");

a = scan.nextFloat();

System.out.print("What is the second number? ");

b = scan.nextFloat();

res = a * b;

System.out.print("Answer " + res);

break;

case '4':

System.out.print("What is the first number? ");

a = scan.nextFloat();

System.out.print("What is the second number? ");

b = scan.nextFloat();

if(b == 0){

System.out.println("Im sorry, you can't divide by 0.");

}

else{

}

res = a / b;

System.out.print("Answer:" + res);

break;

case '5':

System.out.print("What is the first number? ");

a = scan.nextFloat();

System.out.print("What is the second number? ");

b = scan.nextFloat();

double randomVal = Math.random();

double randomNumber = (randomVal * (b - a)) + a;

System.out.print("Result = " + randomNumber);

break;

default : System.out.print("That is not a valid choice. Please try again!");

break;

}

System.out.print(" --------------------------------------- ");

}while(choice != 5);

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!