This problem was solved nicely, but how would you go about adding a swtich state
ID: 3540948 • Letter: T
Question
This problem was solved nicely, but how would you go about adding a swtich statement to determin which menu option the user requested to the code?
Write an application that prompts the user for two integers and then prompts the user to enter an option as follows: 1 to add the two integers, 2 to subtract the second integer from the first, 3 to multiply the integers. and 4 to divide the first integer by the second. Display an error message if the user enters an option other than 1 through 4 or if the user chooses the divide option but enters 0 for the second integer. Otherwise, display the results of the arithmetic.
Explanation / Answer
please rate - thanks
you didn't say what to do with division mixed arithmetic or integer, I made them mixed
import java.util.Scanner;
public class main
{public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n1,n2,op;
System.out.print("Enter 1st operand: ");
n1=in.nextInt();
System.out.print("Enter 2nd operand: ");
n2=in.nextInt();
System.out.println("Enter operation");
System.out.println("1 add the two integers");
System.out.println("2 subtract the second integer from the first");
System.out.println("3 multiply the integers");
System.out.println("4 divide the first integer by the second");
op=in.nextInt();
switch(op)
{case 1:System.out.println(n1+" + "+n2+" = "+(n1+n2));
break;
case 2: System.out.println(n1+" - "+n2+" = "+(n1-n2));
break;
case 3: System.out.println(n1+" * "+n2+" = "+(n1*n2));
break;
case 4: if(n2==0)
System.out.println(n1+" / "+n2+" = Cannot divide by 0");
else
System.out.println(n1+" / "+n2+" = "+((double)n1/n2));
break;
default:System.out.println("Invalid operation");
}
}
}
-------------------------------------
can also do--see division --division by 0, goes into default
import java.util.Scanner;
public class main
{public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n1,n2,op;
System.out.print("Enter 1st operand: ");
n1=in.nextInt();
System.out.print("Enter 2nd operand: ");
n2=in.nextInt();
System.out.println("Enter operation");
System.out.println("1 add the two integers");
System.out.println("2 subtract the second integer from the first");
System.out.println("3 multiply the integers");
System.out.println("4 divide the first integer by the second");
op=in.nextInt();
switch(op)
{case 1:System.out.println(n1+" + "+n2+" = "+(n1+n2));
break;
case 2: System.out.println(n1+" - "+n2+" = "+(n1-n2));
break;
case 3: System.out.println(n1+" * "+n2+" = "+(n1*n2));
break;
case 4: if(n2!=0)
{System.out.println(n1+" / "+n2+" = "+((double)n1/n2));
break;
}
default:System.out.println("Invalid operation");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.