a simple calculator with switch case - java

I have a problem. In class we have to do a simple calculator, and my problem is that I wanna write a number, then the operator, then again a number. Somehow my code doesn't work. I can enter the first number but then my program closes :/ Why is that? Is it because I used the data type string?
Thanks to everyone in advance!!
Here is my code:
import java.util.Scanner;
import java.math.*;
public class Calculatrice
{
public static void main(String args[])
{
double num1;
Scanner keyb = new Scanner(System.in);
System.out.println("Calculette Simple");
System.out.print("Valeur actuelle: ");
num1 = keyb.nextDouble();
System.out.print("Entrez un operateur: ");
String i;
i = keyb.nextLine();
double result = 0;
switch (i)
{
case "+":
result = result + num1;
break;
case "-":
result = result - num1;
break;
case "*":
result = result * num1;
break;
case "/":
result = result / num1;
break;
case "sqrt":
result = Math.sqrt(result);
break;
case "c":
result = 0;
break;
case "x":
System.exit(0);
break;
case "^":
result = Math.pow(result,num1);
break;
default:
System.out.println("Valeurs acceptees: +, -, *, /, ^, sqrt, c, x");
break;
}
keyb.close();
}
}

You need a loop: you need to read data from command line until a condition is verified, in order to read more then one string (number, operator or whatever you want). Then try something like this :
// your initialization of scanner
i = keyb.nextLine();
double result = 0;
while (!i.equals("end")) { // I use this as exit condition, but you can use whatever you want
switch (i) {
case "+":
result = result + num1;
break;
case "-":
result = result - num1;
break;
case "*":
result = result * num1;
break;
case "/":
result = result / num1;
break;
case "sqrt":
result = Math.sqrt(result);
break;
case "c":
result = 0;
break;
case "x":
System.exit(0);
break;
case "^":
result = Math.pow(result, num1);
default:
System.out.println("Valeurs acceptees: +, -, *, /, ^, sqrt, c, x");
}
}
// close scanner

you need some loop with exit condition (I belive it's 'x' in input)
something like
while (!"x".equals(i)) {
switch (i)
...
}

The program takes the value of both the numbers (entered by user) and then user is asked to enter the operation (+, -, * and /), based on the input program performs the selected operation on the entered numbers using switch case.
import java.util.Scanner;
public class JavaExample {
public static void main(String[] args) {
double num1, num2;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number:");
/* We are using data type double so that user
* can enter integer as well as floating point
* value
*/
num1 = scanner.nextDouble();
System.out.print("Enter second number:");
num2 = scanner.nextDouble();
System.out.print("Enter an operator (+, -, *, /): ");
char operator = scanner.next().charAt(0);
scanner.close();
double output;
switch(operator)
{
case '+':
output = num1 + num2;
break;
case '-':
output = num1 - num2;
break;
case '*':
output = num1 * num2;
break;
case '/':
output = num1 / num2;
break;
/* If user enters any other operator or char apart from
* +, -, * and /, then display an error message to user
*
*/
default:
System.out.printf("You have entered wrong operator");
return;
}
System.out.println(num1+" "+operator+" "+num2+": "+output);
}
}

Related

java while loop with if/else statement, else argument runs forever instead of restarting while loop

So I have an assignment where I am supposed to prompt the user to enter an arithmetic operator, and then 2 numbers, and produce the result; i.e. user enters /, 20, 2 and the OUTPUT should be 10. I am using checks to ensure the proper value types are entered by the user, and my check for the integers entered runs forever if the else statement is activated. I am not sure where I am going wrong here. any guidance would be greatly appreciated.
import java.util.Scanner;
public class mainClass {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
boolean charCheck = true; //for verifying user arithmetic input
boolean numCheck = true; //for verifying user int input
boolean sysCheck = true; //for program outer while loop
int n1 = -1; //user entered number 1
int n2 = -2; //user entered number 2
char x = ' '; //user entered arithmetic operator
while (sysCheck == true)
{
while (charCheck == true)
{
System.out.println("Please enter either +, -, *, /to proceed. Enter x to end the program");
x = input.next().charAt(0);
switch(x) //check input validity for x before the program proceeds
{
case '+':
case '-':
case '*':
case '/':
System.out.println(x);
charCheck = false;
break;
case 'x':
System.exit(0);
break;
default:
System.out.print("That is an invalid entry. ");
}
}
System.out.println("Now, please enter 2 numbers, seperated by a space: ");
while(numCheck)
{
if(input.hasNextInt())
{
n1 = input.nextInt();
n2 = input.nextInt();
System.out.println(n1 + " " + n2);
numCheck = false;
}
else
System.out.print("That is an invalid entry. ");
}
switch(x) //check input validity for x before the program proceeds
{
case '+':
System.out.print("The result is: " + (n1 + n2));
break;
case '-':
System.out.print("The result is: " + (n1 - n2));
break;
case '*':
System.out.print("The result is: " + (n1 * n2));
break;
case '/':
System.out.print("The result is: " + (n1 / n2));
break;
}
}
}
}
After playing around with the code more and researching more, I found the solution. the issue I was having was due to not including the line
input.next(); in my else statement (input is the name of my scanner, if you named your scanner something else, that name would be in it's place)
while(numCheck)
{
System.out.println("Now, please enter 2 numbers, seperated by a space: ");
if(!input.hasNextInt())
{
System.out.println("That is an invalid entry. ");
input.next();
}
else
{
n1 = input.nextInt();
n2 = input.nextInt();
numCheck = false;
}
}

How to store value in calc and continue counting?

How to modify the code so I can continuously count? So for example 2+3=5, and than -1 =4, until i press q to exit program ?? Please some simple solution for beginners. Thank you.
import java.util.Objects;
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
do {
System.out.println("Enter first number:");
double num1 = sc.nextDouble();
System.out.println("Enter second number");
double num2 = sc.nextDouble();
System.out.println("Select operator (+,-,*,/) or enter q to exit:");
char operator = sc.next().charAt(0);
switch (operator) {
case '+':
System.out.println("Result =" + Equasion.sum(num1, num2));
break;
case '-':
System.out.println(Equasion.substract(num1, num2));
break;
case'/':
if (num2 == 0) {
System.out.println("Divide by zero problem");
} else System.out.println(Equasion.divide(num1, num2));
case '*':
System.out.println(Equasion.multiply(num1, num2));
break;
case 'q':
System.exit(0);
}
System.out.println("Press any key to continue or q to quit");
} while (!Objects.equals(ExitProg.exitProg(), 'q'));
}
}
Correct me if I'm wrong but you should move the first lines outside the while loop then overwrite the values of num1 and num2 every iteration (num2 becomes num1, then the user inputs another num2)

I made a CLI calculator and I am wondering, how can I have the program accept numbers indefinetly until the user inputs a stop command?

You probably understand that I am a beginner, and I know that we aren't really liked by the community.
I made a multi purpose calculator a while back and now I want to expand it. In this question I will be focusing only on one class.
import java.util.Scanner;
public class Calculator {
public static void calcMenu(Scanner input){
Scanner oper = new Scanner(System.in);
System.out.println("Please input the First number:");
double anum = input.nextDouble();
System.out.println("Please input on of the following operations:");
System.out.println("+");
System.out.println("-");
System.out.println("*");
System.out.println("/");
String equ = oper.nextLine();
System.out.println("Please input the Second number:");
double bnum = input.nextDouble();
switch (equ){
case "+":
System.out.println(anum + bnum);
break;
case "-":
System.out.println(anum - bnum);
break;
case "*":
System.out.println(anum * bnum);
break;
case "/":
System.out.println(anum / bnum);
break;
}
}
}
In this Java class, the program can solve equations only with two numbers. I would like to make it like in a standard calculator, where you can input the numbers as much as you want. I would like to do it until the user types something like "done" and the application will return to the main menu.
This is probably a very nooby question but please help. And if you want to see the whole application: here's the link
This will help you out! :)
import java.util.InputMismatchException;
import java.util.Scanner;
public class Calculator {
private static double answer;
private static boolean done = false;
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
try {
new Calculator().calcExpression();
} catch (InputMismatchException e) {
System.out.println("An error occurred. ");
}
}
private void calcExpression() throws InputMismatchException {
System.out.println("Enter Your Expression Here:");
System.out.print("Num: ");
double firstNum = in.nextDouble();
in.nextLine();
while (!done) {
System.out.print("Operator: ");
String operand = in.nextLine();
if (operand.equals("=")) {
break;
}
System.out.print("Num: ");
double secondNum = in.nextDouble();
in.nextLine();
calculate(firstNum, operand, secondNum);
firstNum = answer;
}
System.out.printf("Answer is %.2f", answer);
}
private void calculate(double num1, String equ, double num2) {
switch (equ)
{
case "/":
answer = (num1 / num2);
break;
case "*":
answer = (num1 * num2);
break;
case "+":
answer = (num1 + num2);
break;
case "-":
answer = (num1 - num2);
break;
case "=":
done = true;
break;
}
}
}

How to use math operators from commandline in program?

I try to calculate digits (in my calculator) in args from commandline. Example:
args[0] = 2*3;
String result = method(args[0]);
System.out.println(result) // should be 6
I don't know how to use my char between two digits example "+", "-". I can't use loops. My method idea is use charAt like:
char a = arg.charAt(0);
char b = arg.charAt(1);
char c = arg.charAt(2);
But I don't know to change my b char (*) to do calculation.
You are not passing the value correctly. Your input is a String, right? Your code shows an integer expression.
args[0] = "2*3"; //note that this changed to a string
double result = parse(args[0]);
System.out.println(result) // should be 6
Then you can parse your string in your method:
double parse(String str){
int num1 = Integer.valueOf(str.substring(0,1));
char operator = str.charAt(1);
int num2 = Integer.valueOf(str.substring(2,3));
switch(operator){
case '+': return num1+num2;
case '-': return num1-num2;
case '*': return num1*num2;
case '/': return num1/num2;
default: throw new IllegalArgumentException();
}
}
Running System.out.println(parse("2*3")); prints 6.0 with my code.
Of course this only works with operands that have exactly one digit. But that's a restriction that comes from your charAt idea.
I'm not normally using JAVA, but..
You will get the input as a string, if you run a process like this:
> MyCalculator 2*3
now, you want to separate this string into three parts:
Number1, Operation, Number2
for this you can do something like:
String[] parts = args[0].split("\\*");
Double Number1 = Double.parseDouble( parts[0])
Double Number2 = Double.parseDouble( parts[1])
now, you may notice that you'll be missing the operator..
so you want locate it and fetch it, or you can do something like this:
if( args[0].indexOf("*") > -1)
{
System.out.println(Number1 * Number2);
}
edit:
for more flexibillity, you may want to do it the opposite way around:
if( args[0].indexOf("*") > -1)
{
String[] parts = args[0].split("\\*");
Double Number1 = Double.parseDouble( parts[0])
Double Number2 = Double.parseDouble( parts[1])
System.out.println(Number1 * Number2);
}
if( args[0].indexOf("/") > -1)
{
String[] parts = args[0].split("/");
Double Number1 = Double.parseDouble( parts[0])
Double Number2 = Double.parseDouble( parts[1])
System.out.println(Number1 / Number2);
}
etc...
notice that "-" will be especially annoying
Its not the best solution but it works, you can enter numbers of any length.
String[] number = args[0].split("[*]|[/]|[+]|[-]");
int stringLength = args[0].length();
int operatorBeginning = number[0].length();
int operatorEnd = stringLength - number[1].length();
String operator = args[0].substring(operatorBeginning,operatorEnd);
double answer = 0;
switch(operator) {
case "*":
answer = Integer.valueOf(number[0]) * Integer.valueOf(number[1]);
break;
case "/":
answer = Integer.valueOf(number[0]) / Integer.valueOf(number[1]);
break;
case "+":
answer = Integer.valueOf(number[0]) + Integer.valueOf(number[1]);
break;
case "-":
answer = Integer.valueOf(number[0]) - Integer.valueOf(number[1]);
break;
default:
System.out.println("Wrong operator");
break;
}
System.out.println(answer);

Calculator_Switch JavaFundamental

Hello I have tried syntax for calculator, with char for operand
but the result always error.
I'm using eclipse (Luna). there are no error or warning message on it.
Syntax
Scanner in = new Scanner(System.in);
int answer = 0;
System.out.println("Enter a number:");
int num1 = in.nextInt();
System.out.println("Enter another number:");
int num2 = in.nextInt();
System.out.println("Enter the operand:");
char input =(char) in.nextInt();
switch (input){
case'*':
answer = num1 * num2;
break;
case '/':
answer = num1/num2;
break;
case '%':
answer = num1%num2;
break;
case '+':
answer = num1 +num2;
break;
case '-':
answer = num1-num2;
break;
default:
System.out.println("Invalid Command");
}
System.out.println("The result is: " + answer);
Debugging
Input number, another number and an operand:
and the error:
InputMismatchException
Just change this line: char input =(char) in.nextInt(); for this char input = in.next().charAt(0)...and you are good to go!

Categories

Resources