logical bug in my code in java... in switch case - java

package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
int operator;
double number1, number2, result;
boolean ask = true;
while (ask) {
System.out.println("please select your operator:\n"
+ "1 for +\n" +
"2 for -\n" +
"3 for *\n" +
"4 for %\n" +
"");
operator = myScanner.nextInt();
System.out.println("you chose " + operator + " operator babe");
System.out.println("please enter your first number");
Scanner numberScanner = new Scanner(System.in);
number1 = numberScanner.nextDouble();
System.out.println("please enter your second number");
Scanner numberScanner2 = new Scanner(System.in);
number2 = numberScanner2.nextDouble();
switch (operator) {
case 1:
result = number1 + number2;
System.out.println("result is:" + result);
break;
case 2:
result = number1 - number2;
System.out.println("result is:" + result);
break;
case 3:
result = number1 * number2;
System.out.println("result is:" + result);
break;
case 4:
result = number1 / number2;
System.out.println("result is:" + result);
break;
default:
System.out.println("you chosen the wrong operator babe :)");
break;
}
System.out.println("do yo want to continue?\n" +
"y for yes\n" +
"n for no\n");
char askInput = myScanner.next().charAt(0);
if (askInput=='n') ask=false;
}
}
}
i got trouble in my switch case
if i press any number or letter somthing like 5 or 6 or... it should print you chose wrong operator.
i think problem is in my default but i don't know where is it?

Just reorder your code like this
`public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
int operator;
double number1, number2, result;
boolean ask = true;
while (ask) {
System.out.println("please enter your first number");
Scanner numberScanner = new Scanner(System.in);
number1 = numberScanner.nextDouble();
System.out.println("please enter your second number");
Scanner numberScanner2 = new Scanner(System.in);
number2 = numberScanner2.nextDouble();
System.out.println("please select your operator:\n"
+ "1 for +\n"
+ "2 for -\n"
+ "3 for *\n"
+ "4 for %\n"
+ "");
operator = myScanner.nextInt();
switch (operator) {
case 1:
result = number1 + number2;
System.out.println("result is:" + result);
break;
case 2:
result = number1 - number2;
System.out.println("result is:" + result);
break;
case 3:
result = number1 * number2;
System.out.println("result is:" + result);
break;
case 4:
result = number1 / number2;
System.out.println("result is:" + result);
break;
default:
System.out.println("you chosen the wrong operator babe :)");
break;
}
System.out.println("you chose " + operator + " operator babe");
System.out.println("do yo want to continue?\n"
+ "y for yes\n"
+ "n for no\n");
char askInput = myScanner.next().charAt(0);
if (askInput == 'n') {
ask = false;
}
}
}`
and you'll be fine

as for my comment, if you want to validate the input the user does (for the option) before having the user input another 2 numbers, than, yeah you should actually programm it that way that the validation goes RIGHT AFTER the first userinput. Here´s a slightly corrected version of your code.
public static void main(String[] args) {
int operator;
double result;
boolean ask = true;
Scanner numberScanner = new Scanner(System.in);
while (ask) {
System.out.println(
"please select your operator:\n" + "1 for +\n" + "2 for -\n" + "3 for *\n" + "4 for %\n" + "");
operator = numberScanner.nextInt();
System.out.println("you chose " + operator + " operator babe");
// Here was your "Mistake". You instantly started asking the user for another input,
// but actually wanted to ahve the switch statment here
switch (operator) {
case 1:
result = get_num1(numberScanner) + get_num2(numberScanner);
System.out.println("result is:" + result);
break;
case 2:
result = get_num1(numberScanner) - get_num2(numberScanner);
System.out.println("result is:" + result);
break;
case 3:
result = get_num1(numberScanner) * get_num2(numberScanner);
System.out.println("result is:" + result);
break;
case 4:
result = get_num1(numberScanner) % get_num2(numberScanner);
System.out.println("result is:" + result);
break;
default:
System.out.println("you chosen the wrong operator babe :)");
break;
}
System.out.println("do yo want to continue?\n" + "y for yes\n" + "n for no\n");
char askInput = numberScanner.next().charAt(0);
if (askInput == 'n')
ask = false;
}
}
public static double get_num1(Scanner scanner) {
System.out.println("please enter your first number");
return scanner.nextDouble();
}
public static double get_num2(Scanner scanner) {
System.out.println("please enter your second number");
return scanner.nextDouble();
}

simply you could validate the operator while you assign it with the input.
for example use if condition and check whether its between 1 and 5 and if not print whatever you want

2 things:
you dont need 2 scanners using only one will be enough
the code is behaving so because you go into the switch case AFTER asking the numbers you want to operate...
some condition like:
operator = myScanner.nextInt();
if (operator < 1 || operator > 4) {
}
may help....

Related

How to make a loop for this script?

I am working on a simple/scientific calculator in java, and I am having trouble putting this in a while loop so the user can continuously use the calculator. I've tried putting it in different places in the code, but it either repeats the input section or doesn't repeat anything. Any tips? Here is my code below:
static Scanner s1 = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Welcome to my calculator:");
String operator = "";
Scanner op = new Scanner(System.in);
System.out.println("Type 1 if you wish to use the Standard calculator, 2 for the Scientific calculator, or QUIT if you wish to quit the program.");
operator = op.nextLine();
if (operator.equals("1")) {
System.out.println(standard());
}
if (operator.equals("2")) {
System.out.println(scientific());
}
if (operator.equals("QUIT")) {
System.out.print("System quit");
}
}
public static int standard() {
//The system will print 0 at the end to show that it's working
System.out.println("Standard Calculator chosen.");
System.out.println("Type 1 if you wish to use addition, 2 for subtraction, 3 for multiplication, 4 for exponent, 5 for division, or 6 for mod.");
int input2 = s1.nextInt();
int num1 = 0;
int num2 = 0;
//String loop = "";
switch (input2) {
case 1:
System.out.println("(Add chosen) Please enter the first value: ");
num1 = s1.nextInt();
System.out.println("Please enter the second value: ");
num2 = s1.nextInt();
System.out.println("Addition - (" + num1 + "+" + num2 + ") = " + addExact(num1, num2));
break;
case 2:
System.out.println("(Sub chosen) Please enter the first value: ");
num1 = s1.nextInt();
System.out.println("Please enter the second value: ");
num2 = s1.nextInt();
System.out.println("Subtration - (" + num1 + "-" + num2 + ") = " + subtractExact(num1, num2));
break;
case 3:
System.out.println("(Multi chosen) Please enter the first value: ");
num1 = s1.nextInt();
System.out.println("Please enter the second value: ");
num2 = s1.nextInt();
System.out.println("Multiplication - (" + num1 + "*" + num2 + ") = " + multiplyExact(num1, num2));
break;
case 4:
System.out.println("(Exp chosen) Please enter the first value: ");
num1 = s1.nextInt();
System.out.println("Please enter the exponent: ");
num2 = s1.nextInt();
System.out.println("Exponent - (" + num1 + "^" + num2 + ") = " + Math.pow(num1, num2));
break;
case 5:
System.out.println("(Div chosen) Please enter the first value: ");
num1 = s1.nextInt();
System.out.println("Please enter the second value: ");
num2 = s1.nextInt();
System.out.println("Division - (" + num1 + "/" + num2 + ") = " + floorDiv(num1, num2));
break;
case 6:
System.out.println("(Mod chosen) Please enter the first value: ");
num1 = s1.nextInt();
System.out.println("Please enter the second value: ");
num2 = s1.nextInt();
System.out.println("Mod - (" + num1 + "%" + num2 + ") = " + floorMod(num1, num2));
break;
}
return (0);
}
public static double scientific() {
//The system will print 0.0 at the end to show that it's working
System.out.println("Scientific Calculator chosen.");
System.out.println("Type 1 for sin, 2 for cos, 3 for tan, 4 for floor, 5 for ceil, 6 for square root, 7 for cube root, 8 for rounding, 9 for min, 10 for max.");
int input2 = s1.nextInt();
double val1 = 0.0;
double val2 = 0.0;
switch (input2) {
case 1:
System.out.println("(Sin chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Sin - (" + val1 + ") = " + sin(val1));
break;
case 2:
System.out.println("(Cos chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Cos - (" + val1 + ") = " + cos(val1));
break;
case 3:
System.out.println("(Tan chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Tan - (" + val1 + ") = " + tan(val1));
break;
case 4:
System.out.println("(Floor chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Floor - (" + val1 + ") = " + Math.floor(val1));
break;
case 5:
System.out.println("(Ceil chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Ceil - (" + val1 + ") = " + Math.ceil(val1));
break;
case 6:
System.out.println("(Square root chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Square root - (" + val1 + ") = " + sqrt(val1));
break;
case 7:
System.out.println("(Cube root chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Cube root - (" + val1 + ") = " + cbrt(val1));
break;
case 8:
System.out.println("(Round chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Round - (" + val1 + ") = " + round(val1));
break;
case 9:
System.out.println("(Min chosen) Please enter the 1st value :");
val1 = s1.nextDouble();
System.out.println("Enter the 2nd value: ");
val2 = s1.nextDouble();
System.out.println("Minimum - (" + val1 + "," + val2 + ") = " + min(val1,val2));
break;
case 10:
System.out.println("(Max chosen) Please enter the 1st value :");
val1 = s1.nextDouble();
System.out.println("Enter the 2nd value: ");
val2 = s1.nextDouble();
System.out.println("Maximum - (" + val1 + "," + val2 + ") = " + max(val1,val2));
break;
}
return val2;
}
}
}
You need to do something as follows, as you want to repeat all the process until the user choose to QUIT the calculator app:
public static void main(String[] args) {
System.out.println("Welcome to my calculator:");
String operator = "";
while (!operator.equals("QUIT")) {
Scanner op = new Scanner(System.in);
System.out.println("Type 1 if you wish to use the Standard calculator, 2 for the Scientific calculator, or QUIT if you wish to quit the program.");
operator = op.nextLine();
if (operator.equals("1")) {
System.out.println(standard());
}
if (operator.equals("2")) {
System.out.println(scientific());
}
if (operator.equals("QUIT")) {
System.out.print("System quit");
}
}
}
output:
Welcome to my calculator:
Type 1 if you wish to use the Standard calculator, 2 for the Scientific calculator, or QUIT if you wish to quit the program.
1
Standard Calculator chosen.
Type 1 if you wish to use addition, 2 for subtraction, 3 for multiplication, 4 for exponent, 5 for division, or 6 for mod.
1
(Add chosen) Please enter the first value:
1
Please enter the second value:
2
Addition - (1+2) = 3
0
Type 1 if you wish to use the Standard calculator, 2 for the Scientific calculator, or QUIT if you wish to quit the program.
Here's a solution for your "main" method that:
uses a "while" loop and a boolean value "keepGoing" to decide if it should loop again (or exit)
uses a "switch" statement to handle calling different functions based on input
if "QUIT" input, it sets "keepGoing = false" so that the "while" loop will exit
defines one Scanner, and names it clearly ("scanner")
passes that single Scanner object to the methods which need it (standard and scientific)
Two other changes worth making:
remove the global static Scanner s1 – don't use global variables, it will lead to hard-to-find problems in your code
edit those method signatures to accept a Scanner parameter:
public static int standard(Scanner s1)`
public static double scientific(Scanner s1)
Here's the code:
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to my calculator:");
String prompt = "Type 1 if you wish to use the Standard calculator, " +
"2 for the Scientific calculator, or " +
"QUIT if you wish to quit the program.";
boolean keepGoing = true;
while (keepGoing) {
System.out.println(prompt);
switch (scanner.nextLine()) {
case "1" -> System.out.println(standard(scanner));
case "2" -> System.out.println(scientific(scanner));
case "QUIT" -> {
System.out.print("System quit");
keepGoing = false; // this ejects from the while loop
}
}
}

How to fix exception handling issue in switch case statement?

I am working on project for class, where we were tasked to design a calculator program with a menu containing 5 options. I am facing an issue when I am trying to code to catch if the user inputs a choice that is not between 1 and 5. Currently if the user inputs a number between 6 to 9. The exception will be caught the first time and an error message which says to enter a choice between 1 and 5 will be displayed and a message to re enter will appear. However if the user continues to enter a number between 6 to 9, the error message is not displayed and the main menu appears. I am also trying to catch when a string is entered as input instead of a choice between 1 and 5 and display a different error message saying the user has entered an invalid input and then ask the user to re enter, however when a string is entered as the choice I get an input mismatch exception error but when a string is entered instead of a float after the operation has been chosen, then the correct error message is displayed.
I am a beginner to Java and am open to all suggestions but if it is possible I would like to keep my code somewhat similar to way it is written currently.
static void promptEnterKey() {
System.out.println("Press enter key to continue ...");
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
}
public static void main(String[] args) {
float Firstnum, Secondnum, Solution;
int choice;
Scanner scan = new Scanner(System.in);
do {
System.out.printf("Welcome to Paul's Handy Calculator\n\n (1) Addition\n "
+ "(2) Subtraction\n (3) Multiplication\n (4) Division\n (5) Exit\n\n");
System.out.printf("What would you like to do? ");
choice = scan.nextInt();
try {
if (choice < 1 || choice > 5) {
System.out.printf("You have not entered a number between 1 and 5. "
+ "Try again.\n");
System.out.printf("Enter your choice between 1 and 5 only: \n");
choice = scan.nextInt();
continue;
}
switch (choice) {
case 1:
System.out.print("Please enter two floats to add, "
+ "separated by a space: ");
Firstnum = scan.nextFloat();
Secondnum = scan.nextFloat();
Solution = Firstnum + Secondnum;
System.out.println("Result of adding " + Firstnum + " and "
+ Secondnum + " is " + Solution + "\n");
promptEnterKey();
break;
case 2:
System.out.println("Please enter two floats to subtract, "
+ "separated by a space: ");
Firstnum = scan.nextFloat();
Secondnum = scan.nextFloat();
Solution = Firstnum - Secondnum;
System.out.println("Result of subtracting " + Firstnum
+ " and " + Secondnum + " is " + Solution + "\n");
promptEnterKey();
break;
case 3:
System.out.print("Please enter two floats to multiply, "
+ "separated by a space: ");
Firstnum = scan.nextFloat();
Secondnum = scan.nextFloat();
Solution = Firstnum * Secondnum;
System.out.print("Result of multiplying " + Firstnum + " and "
+ Secondnum + " is " + Solution + "\n");
promptEnterKey();
break;
case 4:
System.out.print("Please enter two floats to divide, "
+ "separated by a space: ");
Firstnum = scan.nextFloat();
Secondnum = scan.nextFloat();
if (Secondnum == 0) {
System.out.println("You cannot divide by zero, "
+ "please enter another number to divide by");
Secondnum = scan.nextFloat();
}
Solution = Firstnum / Secondnum;
System.out.println("Result of dividing " + Firstnum + " and "
+ Secondnum + " is " + Solution + "\n");
promptEnterKey();
break;
case 5:
System.out.println("Thank You for using Paul's Handy Calculator");
System.exit(0);
break;
default:
}
} catch (InputMismatchException ex) {
System.out.println("You have entered an invalid choice. Try again. ");
String flush =scan.next();
}
} while (choice != 5);
}
You just need to move your welcome message outside of the do-while, move your initial scan.nextInt() call inside the try block, and remove your scan.nextInt() call inside your if statement:
// Moved welcome message outside of do-while
System.out.printf("Welcome to Paul's Handy Calculator\n\n (1) Addition\n "
+ "(2) Subtraction\n (3) Multiplication\n (4) Division\n (5) Exit\n\n");
System.out.printf("What would you like to do? ");
do {
try {
// Moved scan.nextInt inside of try block
choice = scan.nextInt();
if (choice < 1 || choice > 5) {
System.out.printf("You have not entered a number between 1 and 5. " + "Try again.\n");
System.out.printf("Enter your choice between 1 and 5 only: \n");
// Removed nextInt call
continue;
}
...

Calling variable when using Scanner Class and Multiple Classes

Trying to call the total value from the operatorSelection class while that class references what the user enters as the operator.
I want it to end up coming out as number1 (operator chosen) number2...= total.
Not sure how to call class so that it prints the " System.out.println(number1+" "+operator+" "+number2+" "+operator+" "+number2+ " = "+ total); " correctly.
Any knowledge would be greatly appreciated on the subject.
Thanks.
import java.util.Scanner;
class NumbersEntered
{
public void operatorSeletion(double number1, double number2, double number3, char operator)
{
double total = 0;
switch(operator)
{
case '+':
total = number1 + number2 + number3;
break;
case '-':
total = number1 - number2 - number3;
break;
case '*':
total = number1 * number2 * number3;
break;
case '/':
total = number1 / number2 / number3;
break;
default:
System.out.println("You have entered incorrectly. Please try again.");
return;
}
}
}
public class JavaPresentation_KS {
public static void main(String[] args) {
NumbersEntered nums = new NumbersEntered();
Scanner equation = new Scanner(System.in);
System.out.println("Enter first number: ");
double number1 = equation.nextDouble();
System.out.println("Enter second number: ");
double number2 = equation.nextDouble();
System.out.println("Enter third number: ");
double number3 = equation.nextDouble();
System.out.println("Enter an operator (+, -, *, /): ");
char operator = equation.next().charAt(0);
System.out.println(number1+" "+operator+" "+number2+" "+operator+" "+number2+ " = "+ total);
}
}
Your problem is that you declare the total variable within the operatorSeletion method, and you try to access it without specifying it's location. You need to declare the total variable as a field, and then access it at its location (new NumbersEntered().total). Also, you never invoke operatorSeletion, which might help ;)
class NumbersEntered {
public double total = 0; //declare as accessable field
public void operatorSeletion(double number1, double number2, double number3, char operator)
{
switch(operator)
{
case '+':
total = number1 + number2 + number3;
break;
case '-':
total = number1 - number2 - number3;
break;
case '*':
total = number1 * number2 * number3;
break;
case '/':
total = number1 / number2 / number3;
break;
default:
System.out.println("You have entered incorrectly. Please try again.");
return;
}
}
}
public class JavaPresentation_KS {
public static void main(String[] args) {
NumbersEntered nums = new NumbersEntered();
Scanner equation = new Scanner(System.in);
System.out.println("Enter first number: ");
double number1 = equation.nextDouble();
System.out.println("Enter second number: ");
double number2 = equation.nextDouble();
System.out.println("Enter third number: ");
double number3 = equation.nextDouble();
System.out.println("Enter an operator (+, -, *, /): ");
char operator = equation.next().charAt(0);
nums.operatorSeletion(number1, number2, number3, operator);
//invoke the method
System.out.println(number1 + " " + operator + " " + number2 + " " + operator + " " + number2 + " = " + nums.total);
//Access at location (nums.total)
}

Calculator in Java: How to return to the main menu?

I've writter a calculator program in Java, after a user is done with work,
I want this to happen:
i'll ask if he wants to do more operations, if yes, the program should return to choice input. If no, break the program.
What lines should I add to the code? This is my calc program:
import java.util.*;
class calc
{
public static void main(String ar[])
{
char choice;
Scanner in = new Scanner(System.in);
System.out.println("WELCOME TO SHREYDAN'S CALC 1.0");
System.out.println(" ");
System.out.println("YOU CAN DO THE FOLLOWING:");
System.out.println("+: ADDITION");
System.out.println("-: SUBTRACTION");
System.out.println("*: PRODUCT");
System.out.println("/: QUOTIENT");
System.out.println("#: SQUARE ROOT");
System.out.println("^: POWER");
System.out.println("$: ROUND OFF");
System.out.println("!: FACTORIAL");
System.out.println(" ");
System.out.println("ENTER CHOICE");
choice=in.next().charAt(0);
switch(choice)
{
case '+':
System.out.println("ENTER 2 NUMBERS, USER");
double a=in.nextDouble();
double b=in.nextDouble();
System.out.println("SUM = "+(a+b));
break;
case '-':
System.out.println("ENTER 2 NUMBERS, USER");
double c=in.nextDouble();
double d=in.nextDouble();
System.out.println("SUBTRACTING "+d+" FROM "+c+" ... DIFFERENCE = "+(c-d));
break;
case '*':
System.out.println("ENTER 2 NUMBERS, USER");
double e=in.nextDouble();
double f=in.nextDouble();
System.out.println("PRODUCT = "+(e*f));
break;
case '/':
System.out.println("ENTER 2 NUMBERS, USER");
double g=in.nextDouble();
double h=in.nextDouble();
System.out.println("DIVIDING "+g+" BY "+h+" = "+(g/h));
break;
case '#':
System.out.println("ENTER NO. FOR SQAURE ROOT:");
double sqrt=in.nextDouble();
System.out.println("SQUARE ROOT OF "+sqrt+" = "+Math.sqrt(sqrt));
break;
case '^':
System.out.println("ENTER BASE, USER");
double base=in.nextDouble();
System.out.println("ENTER POWER, USER");
double power=in.nextDouble();
System.out.println(base+" RAISED TO POWER "+power+" = "+Math.pow(base,power));
break;
case '$':
System.out.println("ENTER DECIMAL VALUES TO ROUND OFF");
double deci=in.nextDouble();
System.out.println("THE NEAREST ROUND OFF = "+Math.round(deci));
break;
case '!':
System.out.println("ENTER A NO. FOR FACTORIAL:");
int fact=in.nextInt();
int factorial=1;
for(int i=fact; i>=1;i--)
factorial=factorial*i;
System.out.println(fact+"! = "+factorial);
break;
default:
System.out.println("WRONG CHOICE USER");
}
}
}
while loops are your best bet for this type of problem, just think of a condition which the user can choose to toggle the boolean condition.
for example if the user chooses no on the "continuing of operations" choice, then toggle the boolean to false and exit the while loop to end the program.
You need to wrap the program logic in a loop.
Try using a while loop
public static void main(String args[])
{
boolean doContinue = true;
while(doContinue){
char choice;
Scanner in = new Scanner(System.in);
//program logic
//when the user enters a command to end
// set continue=false
}
}
Maybe put the entire program inside a while loop with a continue to run bool condition which could be set false when they want to quit
You can try the following:
import java.util.*;
class calc {
public static void main(String ar[]) {
char choice;
Scanner in = new Scanner(System.in);
System.out.println("WELCOME TO SHREYDAN'S CALC 1.0");
System.out.println(" ");
boolean loop = true;
while (loop) {
System.out.println("YOU CAN DO THE FOLLOWING:");
System.out.println("+: ADDITION");
System.out.println("-: SUBTRACTION");
System.out.println("*: PRODUCT");
System.out.println("/: QUOTIENT");
System.out.println("#: SQUARE ROOT");
System.out.println("^: POWER");
System.out.println("$: ROUND OFF");
System.out.println("!: FACTORIAL");
System.out.println(" ");
System.out.println("ENTER CHOICE");
choice = in.next().charAt(0);
switch (choice) {
case '+':
System.out.println("ENTER 2 NUMBERS, USER");
double a = in.nextDouble();
double b = in.nextDouble();
System.out.println("SUM = " + (a + b));
break;
case '-':
System.out.println("ENTER 2 NUMBERS, USER");
double c = in.nextDouble();
double d = in.nextDouble();
System.out.println("SUBTRACTING " + d + " FROM " + c + " ... DIFFERENCE = " + (c - d));
break;
case '*':
System.out.println("ENTER 2 NUMBERS, USER");
double e = in.nextDouble();
double f = in.nextDouble();
System.out.println("PRODUCT = " + (e * f));
break;
case '/':
System.out.println("ENTER 2 NUMBERS, USER");
double g = in.nextDouble();
double h = in.nextDouble();
System.out.println("DIVIDING " + g + " BY " + h + " = " + (g / h));
break;
case '#':
System.out.println("ENTER NO. FOR SQAURE ROOT:");
double sqrt = in.nextDouble();
System.out.println("SQUARE ROOT OF " + sqrt + " = " + Math.sqrt(sqrt));
break;
case '^':
System.out.println("ENTER BASE, USER");
double base = in.nextDouble();
System.out.println("ENTER POWER, USER");
double power = in.nextDouble();
System.out.println(base + " RAISED TO POWER " + power + " = " + Math.pow(base, power));
break;
case '$':
System.out.println("ENTER DECIMAL VALUES TO ROUND OFF");
double deci = in.nextDouble();
System.out.println("THE NEAREST ROUND OFF = " + Math.round(deci));
break;
case '!':
System.out.println("ENTER A NO. FOR FACTORIAL:");
int fact = in.nextInt();
int factorial = 1;
for (int i = fact; i >= 1; i--)
factorial = factorial * i;
System.out.println(fact + "! = " + factorial);
break;
default:
System.out.println("WRONG CHOICE USER");
}
System.out.println("Want to calculate more?Y/N");
loop = in.next().charAt(0) == 'Y';
}
}
}

Trouble with basic calculator using switch

I have already researched this question, but could not find an answer that solved my problem. I keep on getting output 0. For this assignment, I'm not allowed to use any methods. In my program, 1+2 equals 0
public static void main(String[] args) {
int result = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number");
int number = sc.nextInt();
System.out.println("Enter operation");
System.out.println("1.+");
System.out.println("2.-");
System.out.println("3.*");
System.out.println("4./");
System.out.println("5.=");
int operation = sc.nextInt();
while (operation != 5) {
System.out.println("Enter next number");
number = sc.nextInt();
System.out.println("Enter operation");
operation = sc.nextInt();
switch (operation) {
case 1:
result += number;
System.out.println("result= " + result);
break;
case 2:
result -= number;
System.out.println("result= " + result);
break;
case 3:
result *= number;
System.out.println("result= " + result);
break;
case 4:
result/ = number;
System.out.println("result= " + result);
break;
}
System.out.println(result);
}
import java.lang.System;
import java.util.Scanner;
public class Java{
public static void main(String args[])
{
int result = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number");
result = sc.nextInt();
System.out.println("Enter operation");
System.out.println("1.+");
System.out.println("2.-");
System.out.println("3.*");
System.out.println("4./");
System.out.println("5.=");
int operation = sc.nextInt();
while (operation != 5) {
System.out.println("Enter next number");
int number = sc.nextInt();
switch (operation) {
case 1:
result += number;
System.out.println("result= " + result);
break;
case 2:
result -= number;
System.out.println("result= " + result);
break;
case 3:
result *= number;
System.out.println("result= " + result);
break;
case 4:
result /= number;
System.out.println("result= " + result);
break;
}
System.out.println(result);
System.out.println("Enter operation");
operation = sc.nextInt();
}
}
}
for the first number and second number you are using the variable number..so u will get Zero.
Your first operation was not being executed.
Try this:
public static void main(String[] args) {
int result = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number");
result = sc.nextInt();
System.out.println("Enter operation");
System.out.println("1.+");
System.out.println("2.-");
System.out.println("3.*");
System.out.println("4./");
System.out.println("5.=");
int operation = sc.nextInt();
while (operation != 5) {
System.out.println("Enter next number");
int operand2 = sc.nextInt();
switch (operation) {
case 1:
result += operand2;
System.out.println("result= " + result);
break;
case 2:
result -= operand2;
System.out.println("result= " + result);
break;
case 3:
result *= operand2;
System.out.println("result= " + result);
break;
case 4:
result /= operand2;
System.out.println("result= " + result);
break;
}
System.out.println("Enter operation");
operation = sc.nextInt();
}
System.out.println("Global result = " + result);
}
}
The problem is that you are reading number and operation twice for the first iteration of the loop instead move the two reading condition after switch case as given below.
public static void main(String[] args) throws java.lang.Exception {
int result = 0;
Scanner sc = new Scanner(System. in );
System.out.println("Enter number");
int number = sc.nextInt();
System.out.println("Enter operation");
System.out.println("1.+");
System.out.println("2.-");
System.out.println("3.*");
System.out.println("4./");
System.out.println("5.=");
int operation = sc.nextInt();
try {
while (operation != 5) {
switch (operation) {
case 1:
result += number;
System.out.println("result= " + result);
break;
case 2:
result -= number;
System.out.println("result= " + result);
break;
case 3:
result *= number;
System.out.println("result= " + result);
break;
case 4:
result /= number;
System.out.println("result= " + result);
break;
}
System.out.println("Enter next number");
number = sc.nextInt();
System.out.println("Enter operation");
operation = sc.nextInt();
}
System.out.println("Final esult is " + result);
} catch (Exception e) {
System.out.println(e);
}
}
Output
Enter number 2
Enter operation 1
1.+
2.-
3.*
4./
5.=
result= 2
Enter next number 5
Enter operation 5
Final result is 2
Demo

Categories

Resources