Simple calculator program in Java - java

I am a newbie coder in Java and I am trying to make this calculator in java where a user can enter two numbers and select the operation to be done on those numbers. However when the code comes to selecting the operator it skips the user input and the if statement and directly implements the else statement.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner Calc = new Scanner(System.in);
int n1;
int n2;
int Answer;
System.out.println("Enter the first number: ");
n1 = Calc.nextInt();
System.out.println("Enter the second number:" );
n2 = Calc.nextInt();
System.out.println("Select the order of operation: ");
char operator = Calc.nextLine().charAt(0);
if (operator == '+') {
Answer = (n1 + n2);
System.out.println("Answer:" + Answer);
}
if (operator == '-') {
Answer = (n1 - n2);
System.out.println("Answer:" + Answer);
}
if (operator == '*') {
Answer = (n1 * n2);
System.out.println("Answer:" + Answer);
}
if (operator == '/') {
Answer = (n1/n2);
System.out.println("Answer:" + Answer);
}
else {
System.out.println("not implemented yet. Sorry!");
}
}
}

Add Calc.nextLine(); after n2 = Calc.nextInt(); to consume the line feed.
You are also not using else if so all those if conditions will be checked even if previous if already matched (resulting in your final else being executed as long as operator not '/').
In this case you should probably just use a switch block.

I made some changes to the code, this should work with you, but I also recommend using a switch.
Scanner Input = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int num1 = Input.nextInt();
System.out.print("Enter an operator: ");
char operator = Input.next().charAt(0);
System.out.print("Enter a second number: ");
int num2 = Input.nextInt();
// this part of decision, it doesn't work.
if ('+' == operator) {
System.out.println("Your result is " + (num1 + num2));
} else if ('-' == operator) {
System.out.println("Your result is " + (num1 - num2));
} else if ('*' == operator) {
System.out.println("Your result is " + (num1 * num2));
} else if ('/' == operator) {
System.out.println("Your result is " + (num1 / num2));
}else {
System.out.println("Your answer is not valid");
}
} catch (InputMismatchException e) {
System.out.println("similar to try and except in Python");
}

Related

Continuous Calculator

I'm making a calculator where you ask two numbers and an operation. If the user wants to continue, ask for a number and an operation. Then, perform the selected operation with the recent result and the new input value.
I'm stuck in storing the result of the last operation to use it for another operation. Here's my code
import java.util.Scanner;
public class practice {
static double add, sub, mul, div;
static double another;
public static void main(String[] args) {
char choose, cont;
Scanner u = new Scanner(System.in);
System.out.print("Enter number 1: ");
double one = Double.parseDouble(u.nextLine());
System.out.print("Enter number 2: ");
double two = Double.parseDouble(u.nextLine());
do {
System.out.print("\nSelect an operation\n[A]Addition\n[B]Subtraction\n[C]Multiplication\n[D]Division");
System.out.print("\n\nChoose: ");
choose = u.next().charAt(0);
if ((choose == 'A') || (choose == 'a')) {
add = one + two;
add += another;
System.out.println("The sum is " + add);
} else if (choose == 'B' || choose == 'b') {
sub = one - two;
sub -= another;
System.out.println("The difference is " + sub);
} else if (choose == 'C' || choose == 'c') {
mul = one * two;
mul *= another;
System.out.println("The product is " + mul);
} else if (choose == 'D' || choose == 'd') {
div = one / two;
div /= another;
System.out.println("The quotient is " + div);
} else {
System.out.println("Invalid Selection");
}
System.out.print("Continue?[Y/N]: ");
cont = u.next().charAt(0);
if (cont == 'Y') {
System.out.print("Enter another number: ");
another = u.nextDouble();
another = another;
} else {
System.out.println("End of Program");
}
} while (cont == 'Y');
}
}
You could put the value of the last value outside of the loop. Here's some pseudo-code to demonstrate what I mean:
variableStore = 0
loop:
perform operations
when printing out results to the user, assign variableStore = result
Next time, variableStore would be the value of the previous result
You don't need all those variables. Variable one always stores the latest result. Also, since your class only contains a single method, namely main, there is no need to declare class member variables. Refer to section 6.3 of the Java Language specification that explains about the scope of variables. The link is for Java 7 but is valid for all java versions.
Here is my rewrite of class practice. Note that I changed the class name to Practice, in keeping with Java naming conventions.
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
char choose, cont = 'Y';
Scanner u = new Scanner(System.in);
System.out.print("Enter number 1: ");
double one = Double.parseDouble(u.nextLine());
double two = 0;
boolean invalidSelection = false;
do {
if (!invalidSelection) {
System.out.print("Enter another number: ");
two = Double.parseDouble(u.nextLine());
}
invalidSelection = false;
System.out.print(
"\nSelect an operation\n[A]Addition\n[B]Subtraction\n[C]Multiplication\n[D]Division");
System.out.print("\n\nChoose: ");
choose = u.nextLine().charAt(0);
if ((choose == 'A') || (choose == 'a')) {
one += two;
System.out.println("The sum is " + one);
}
else if (choose == 'B' || choose == 'b') {
one -= two;
System.out.println("The difference is " + one);
}
else if (choose == 'C' || choose == 'c') {
one *= two;
System.out.println("The product is " + one);
}
else if (choose == 'D' || choose == 'd') {
one /= two;
System.out.println("The quotient is " + one);
}
else {
System.out.println("Invalid Selection");
invalidSelection = true;
continue;
}
System.out.print("Continue?[Y/N]: ");
cont = u.nextLine().charAt(0);
} while (cont == 'Y' || cont == 'y');
System.out.println("End of Program");
}
}
Note, in the above code, that I replaced calls to method next (of class java.util.Scanner) with calls to method nextLine. Refer to this SO question for more details.
Scanner is skipping nextLine() after using next() or nextFoo()?
I recommend that you run the code with a debugger in order to understand how it works.
Here is the output from a sample run.
Enter number 1: 3
Enter another number: 2
Select an operation
[A]Addition
[B]Subtraction
[C]Multiplication
[D]Division
Choose: x
Invalid Selection
Select an operation
[A]Addition
[B]Subtraction
[C]Multiplication
[D]Division
Choose: c
The product is 6.0
Continue?[Y/N]: y
Enter another number: 4
Select an operation
[A]Addition
[B]Subtraction
[C]Multiplication
[D]Division
Choose: b
The difference is 2.0
Continue?[Y/N]: y
Enter another number: 0.5
Select an operation
[A]Addition
[B]Subtraction
[C]Multiplication
[D]Division
Choose: d
The quotient is 4.0
Continue?[Y/N]: n
End of Program
Try this code(it works for me):
import java.util.Scanner;
public class practice {
static double prevAns = 0;
static double another;
static double one;
static double add,sub,mul,div;
static boolean contin = false;
public static void main (String []args){
while(true){
char choose,cont;
Scanner u=new Scanner(System.in);
if (!contin){
System.out.print("Enter number 1: ");
one= Double.parseDouble(u.nextLine());
} else {
one = prevAns;
}
System.out.print("Enter number 2: ");
double two= Double.parseDouble(u.nextLine());
System.out.print("\nSelect an operation\n[A]Addition\n[B]Subtraction\n[C]Multiplication\n[D]Division");
System.out.print("\n\nChoose: ");
choose=u.next().charAt(0);
if((choose=='A')||(choose=='a')){
add = one+two;
prevAns = add;
System.out.println("The sum is "+add);}
else if (choose=='B'||choose=='b') {
sub=one-two;
prevAns = sub;
System.out.println("The difference is "+sub);
}else if (choose=='C'||choose=='c'){
mul=one*two;
prevAns = mul;
System.out.println("The product is "+mul);
}else if(choose=='D'||choose=='d'){
div=one/two;
prevAns = div;
System.out.println("The quotient is "+ div);}
else{
System.out.println("Invalid Selection");
}
System.out.print("Continue?[Y/N]: ");
cont=u.next().charAt(0);
if(cont=='Y'){
contin = true;
} else{
System.out.println("End of Program");
}
}
}
}

Calcu: How to add the operator before each number like a real calc

I'm just trying to build a calculator and I have no idea how to prompt an operator before each number. I'm trying to build a calculator and have as many number inputs as specified but they can cancel out of it by pressing -1 and it will still return the final value.
But i tried using a string statements but I'm new to coding and don't know where to start.
int operator;
int howmany;
int i=0;
int all = 0;
double div;
int scan;
System.out.println("Press 1 for addition, 2 for subtraction, 3 for \n
multiplication 4 for division or 5 for modules");
operator=scanner.nextInt();
if(operator < 1 || operator >5) {System.out.println("Restart
calculator");System.exit(0);}
System.out.println("How many numbers will you be using?");
howmany = scanner.nextInt() -1 ;
if (operator == 1){
System.out.println("Press -1 to cancel ");
while(i <=howmany) {
i++;
System.out.println("Enter number" + i);
System.out.println("So far your numbers is " + all);
scan = scanner.nextInt();
all += scan;
if(i-1 == howmany ) {
System.out.println("Your final answer is " + all);
}
if(scan == -1) {
System.out.println("No more inputs, final answer was " + all);
break;
}
}
}
if (operator == 2){
System.out.println("Press -1 to cancel ");
while(i <=howmany) {
i++;
System.out.println("Enter number" + i);
System.out.println("So far your numbers is " + all);
scan = scanner.nextInt();
all -= scan;
if(i-1 == howmany ) {
System.out.println("Your final answer is " + all);
}
if(scan == -1) {
System.out.println("No more inputs, final answer was " + all);
break;
}
}
}
if (operator == 3){
all = 1;
System.out.println("Press -1 to cancel ");
while(i <=howmany) {
i++;
System.out.println("Enter number" + i);
System.out.println("So far your numbers is " + all);
scan = scanner.nextInt();
all *= scan;
if(i-1 == howmany ) {
System.out.println("Your final answer is " + all);
}
if(scan == -1) {
System.out.println("No more inputs, final answer was " + all);
break;
}
}
}
if (operator == 4){
System.out.println("Press -1 to cancel ");
while(i <=howmany) {
i++;
System.out.println("Enter number" + i);
System.out.println("So far your numbers is " + all);
scan = scanner.nextInt();
all = scan;
if(i-1 == howmany ) {
System.out.println("Your final answer is " + all);
}
if(scan == -1) {
System.out.println("No more inputs, final answer was " + all);
break;
}
}
}
if (operator == 5){
System.out.println("Press -1 to cancel ");
while(i <=howmany) {
i++;
System.out.println("Enter number" + i);
System.out.println("So far your numbers is " + all);
scan = scanner.nextInt();
all %= scan;
if(i-1 == howmany ) {
System.out.println("Your final answer is " + all);
}
if(scan == -1) {
System.out.println("No more inputs, final answer was " + all);
break;
}
}
}
}
}
When you don't know where to start when coding, it can help to write the algorithm in sentences first, and then convert into code. For a calculator program for example, I would start with this basic structure:
// need a data structure to hold all numbers
// need a data structure to hold all operations
while(the user wishes to continue) {
while(the user has not hit =) {
// use the scanner to get the next number (if it's -1, exit program)
// use the scanner to get the next operator (if it's = then exit inner
// loop to report result)
}
// need variable to hold calculation result, instantiate to first number
for(loop through numbers data structure) {
// apply next operator to the running result and next number
}
// report result to user
}
Something else to consider: a calculator should be able to use -1 in calculations. I'm not sure if this is a requirement of what you're working on, so I left it as you described, but what would be more in line with the spirit of a calculator would be to do something like ask the user after each successful calculation if they'd like to continue (y/n).

Scanner skipping nextLine(); after do while loop

as you can probably see I am a newbie in java. Below is a simple calculator program which asks for the user to input a symbol such as + or -. The user then inputs 2 numbers and depending on the operator symbol chosen a method will be called. A do while loop allows the user to repeat the process. The problem is that after the program loops, the following line: "String symb = inp.nextLine();" is skipped. I have already tried searching for a solution however I only found a fix if the nextLine is called after nextInt. Thank you in advance for your patience.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner inp = new Scanner(System.in);
Methods operation = new Methods();
boolean loop = false;
do {
System.out.println("Enter an operator symbol - +, -, * or /");
String symb = inp.nextLine(); //this is the line which is skipped
System.out.println("Enter a number");
int num1 = inp.nextInt();
inp.nextLine();
System.out.println("Enter a second number");
int num2 = inp.nextInt();
inp.nextLine();
switch(symb) {
case "+" :
operation.setA(num1);
operation.setB(num2);
int totalAddition = operation.addNums(num1,num2);
System.out.println("The result is - " + totalAddition);
break;
case "-" :
operation.setA(num1);
operation.setB(num2);
int totalSubtract = operation.subtractNums(num1,num2);
System.out.println("The result is - " + totalSubtract);
break;
case "*" :
operation.setA(num1);
operation.setB(num2);
int totalMult = operation.multNums(num1,num2);
System.out.println("The result is - " + totalMult);
break;
case "/" :
operation.setA(num1);
operation.setB(num2);
int totalDiv = operation.divNums(num1,num2);
System.out.println("The result is - " + totalDiv);
break;
}
System.out.println("Would you like to exit? Y/N");
char ans = inp.next().charAt(0);
if(ans == 'Y' || ans == 'y') {
loop = true;
inp.close();
System.exit(0);
}
else {
loop = false;
}
}
while(loop == false);
}
}

Return to start of the Java code(main menu of calculator)

I am new and somewhat a noob to Java, and I'm trying to make a calculator, didn't test everything to see if it works, but I'm having a problem. I can't seem to figure out how do I get back to the main menu after performing one calculation. I have added that question in the end to make it prompt the user either to exit or continue back to the main menu. I just don't know what to put in the if(whatnow == Y){ wtf am i supposed to do to get back to the main menu?? }. Sorry if it was a bit long or something, but they're really all the same so just skip the calculation thingy. Any help appreciated. I am really new to java and i probably have to write this code all over again.
package practice;
import java.util.Scanner;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int choice;
int firstnumber;
int secondnumber;
int result;
char whatnow;
System.out.println("Welcome to StemCalc Z Edition(Integers only)!");
System.out.println("Made with love and basic Java");
System.out.println("Which math operation would you like to perform?");
System.out.println("");
System.out.println("WARNING: Enter the integer x, press ENTER, then enter y");
System.out.println("");
System.out.println("[1]-Addition (+)");
System.out.println("[2]-Subtraction (-)");
System.out.println("[3]-Multiplication (x)");
System.out.println("[4]-Division (/)");
System.out.println("");
System.out.println("Enter your choice[1-4 or 99]:"); choice = scan.nextInt();
while ((choice < 1 || choice > 4) && choice != 99) {
System.out.println("Please enter 1, 2, 3, 4, or 99: ");
choice = scan.nextInt();
}
if (choice == 1){
System.out.println("Enter two integer to add(x + y)");
firstnumber = scan.nextInt();
secondnumber = scan.nextInt();
result = firstnumber + secondnumber;
System.out.println(firstnumber + " + " + secondnumber + " = " + result);
}
else if (choice == 2) {
System.out.println("Enter two integers to subtract(x - y)");
firstnumber = scan.nextInt();
secondnumber = scan.nextInt();
result = firstnumber - secondnumber;
System.out.println(firstnumber + " - " + secondnumber + " = " + result);
}
else if (choice == 3) {
System.out.println("Enter two integers to multiply(x * y)");
firstnumber = scan.nextInt();
secondnumber = scan.nextInt();
result = firstnumber * secondnumber;
System.out.println(firstnumber + " * " + secondnumber + " = " + result);
}
else if (choice == 4) {
System.out.println("Enter to integers to divide(x / y)");
firstnumber = scan.nextInt();
secondnumber = scan.nextInt();
while (secondnumber == 0) {
System.out.println("ERROR-CANNOT DIVIDE TO ZERO! Type another integer:");
secondnumber = scan.nextInt();
}
result = firstnumber / secondnumber;
System.out.println(firstnumber + " / " + secondnumber + " = " + result);
}
else if (choice == 99) {
System.exit(0);
}
while (choice !=99) {
System.out.println("Do you want to continue calculating? [Y/N]:"); whatnow = scan.next().charAt(0);
if (whatnow == 'Y' || whatnow == 'y') {
}
if (whatnow == 'N' || whatnow == 'n') {
System.exit(0);
}
}
}
}
P.S: I edited the end to look something like this with a while(true) at the beginning:
`while (choice !=99) {
System.out.println("Do you want to continue calculating? [Y/N]:"); whatnow = scan.next().charAt(0);
while(whatnow != 'Y' || whatnow != 'y' || whatnow !='N' || whatnow !='n') {
System.out.println("Enter [Y/N] only:"); whatnow = scan.next().charAt(0);
}
if (whatnow == 'N' || whatnow == 'n') {
System.exit(0);`
You just need to repeat everything you have written until the user insert N. So all you want to do is put everything inside a while(true) loop, whose last instruction will be:
if (whatnow == 'N' || whatnow = 'n') {
System.exit(0);
}
This way, if the user inserts anything besides N or n the loop will bring him back to the main menu printing section, so maybe you would need to add a test on the value of whatnow in the same way you did for choice.
The result will be like this:
public static void main(String[] args){
...
while(true){
System.out.println("Welcome to StemCalc Z Edition(Integers only)!");
...
while (choice !=99) {
System.out.println("Do you want to continue calculating? [Y/N]:"); whatnow = scan.next().charAt(0);
//insert some loop to ensure that the value of whatnow will be either Y or N
if (whatnow == 'N' || whatnow == 'n') {
System.exit(0);
}
}
}
}
EDIT
Here is a sample code of what I anticipated with my last comment:
public static void main(String[] args){
char whatnow = 'Y';
Scanner scan = new Scanner(System.in);
while (whatnow != 'N' && whatnow != 'n') {
int choice = printMenuAndAsk(scan);
if (choice == 99)
break;
else performOperation(choice, scan);
System.out.println("Do you want to continue calculating? [Y/N]:");
whatnow = scan.next().charAt(0);
while(whatnow != 'N' && whatnow != 'Y' && whatnow != 'n' && whatnow != 'y') {
System.out.println("Incorrect answer");
whatnow = scan.next().charAt(0);
}
}
scan.close();
}
public static int printMenuAndAsk(Scanner scan) {
int choice;
System.out.println("Welcome to StemCalc Z Edition(Integers only)!");
...
System.out.println("Enter your choice[1-4 or 99]:");
choice = scan.nextInt();
while ((choice < 1 || choice > 4) && choice != 99) {
System.out.println("Please enter 1, 2, 3, 4, or 99: ");
choice = scan.nextInt();
}
return choice;
}
public static void performOperation(int operation, Scanner scan) {
System.out.println("Enter first:");
int firstnumber = scan.nextInt();
System.out.println("Enter second:");
int secondnumber = scan.nextInt();
if (choice == 1)
System.out.println(firstnumber + " + " + secondnumber + " = " + (firstnumber+secondnumber));
else if (choice == 2)
System.out.println(firstnumber + " - " + secondnumber + " = " + (firstnumber-secondnumber));
else if (choice == 3)
System.out.println(firstnumber + " * " + secondnumber + " = " + (firstnumber*secondnumber));
else if (choice == 4) {
while (secondnumber == 0) {
System.out.println("ERROR-CANNOT DIVIDE TO ZERO! Type another integer:");
secondnumber = scan.nextInt();
}
System.out.println(firstnumber + " / " + secondnumber + " = " + (firstnumber/secondnumber));
}
}
Instead of trying to put a while loop at the end, try to put your entire code in awhile(true) block. Using an if statement at the end, you can ask whether the user wants to continue our not. Exit the loop by using thebreak keyword.
Try to exit like this:
if(input == 'n'){break;}
What this does is that it exits the while loop. You can execute more instructions outside the while block.
You could change it as follows:
Your main method as such:
public static void main(String[] args) {
calc();
}
And then create a method named calc():
public static void calc() {
Scanner scan = new Scanner(System.in);
//the rest of your code
} else if (choice == 99) {
System.exit(0);
}
calc(); //call the method again at the end of your code
//remove your while loop
}

English Language Calculator [java]

Create a java program that will do the following:
a) Read three inputs from the keyboard,
• two input numbers each being a single digit (0…9)
• one character representing one of five operations : + (addition), - (subtraction), * (multiplication), / (division), and ^ (exponentiation)
b) output the description of the operation in plain English as well as the numeric results
import java.util.Scanner;
public class EnglishCalc {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter first number");
int number1 = input.nextInt();
System.out.println("Enter second number");
int number2 = input.nextInt();
System.out.println("Enter operation: +,-,*,/,^");
String operation = input.next();
int output = 0;
if(number1 < 0 || number1 > 9 || number2 < 0 || number2 > 9) {
System.out.println("Number should be between 0 and 10");
}
else if (operation.equals("+"))
{
output = number1 + number2;
System.out.println("Sum of "+number1+" and "+number2+" is: " +output);
}
else if (operation.equals("-"))
{
output = number1 - number2;
System.out.println("Subtraction of "+number2+" from "+number1+" is: " +output);
}
else if (operation.equals("*"))
{
output = number1 * number2;
System.out.println("Product of "+number1+" and "+number2+" is: " +output);
}
else if (operation.equals("/"))
{
if(number2 == 0) {
System.out.println("You cannot divide by 0");
} else {
output = number1/number2;
System.out.println("Division of "+number1+" by "+number2+" is: " +output);
}
}
else if(operation.equals('^'))
{
output = Math.pow((double)number1 , (double)number2);
System.out.println("Value of "+num1+" raised to power of "+num2+" is: " +output);
} else {
System.out.println("Invalid input");
}
}
}
for pow. i tried casting wont work. and if i dont cast, it wont accept int. must be double.
Use
s1.equals(s2)
to compare strings, instead of using:
s1 == s2
This happens because == is used to compare object references (if the are the same object), so it doesn't compare the 'contain' of that object, in this case a String.
Edit
To print each number in 'words', you could use an array:
String[] numbers = {"zero", "one", "two", ... };
and then use them as:
System.out.println(numbers[2] + " plus " + numbers[5] + ...);

Categories

Resources