I'm trying to create a basic calculator in Java. I'm quite new to programming so I'm trying to get used to it.
import java.util.Scanner;
import javax.swing.JOptionPane;
public class javaCalculator
{
public static void main(String[] args)
{
int num1;
int num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println("please enter the first number");
num1 = input.nextInt();
System.out.println("please enter the second number");
num2 = input.nextInt();
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation");
operation = op.next();
if (operation == "+");
{
System.out.println("your answer is" + (num1 + num2));
}
if (operation == "-");
{
System.out.println("your answer is" + (num1 - num2));
}
if (operation == "/");
{
System.out.println("your answer is" + (num1 / num2));
}
if (operation == "*")
{
System.out.println("your answer is" + (num1 * num2));
}
}
}
This is my code. It prompts for the numbers and operation, but displays the answers all together ?
Remove the semi-colons from your if statements, otherwise the code that follows will be free standing and will always execute:
if (operation == "+");
^
Also use .equals for Strings, == compares Object references:
if (operation.equals("+")) {
Here is simple code for calculator so you can consider this
import java.util.*;
import java.util.Scanner;
public class Hello {
public static void main(String[] args)
{
System.out.println("Enter first and second number:");
Scanner inp= new Scanner(System.in);
int num1,num2;
num1 = inp.nextInt();
num2 = inp.nextInt();
int ans;
System.out.println("Enter your selection: 1 for Addition, 2 for substraction 3 for Multiplication and 4 for division:");
int choose;
choose = inp.nextInt();
switch (choose){
case 1:
System.out.println(add( num1,num2));
break;
case 2:
System.out.println(sub( num1,num2));
break;
case 3:
System.out.println(mult( num1,num2));
break;
case 4:
System.out.println(div( num1,num2));
break;
default:
System.out.println("Illigal Operation");
}
}
public static int add(int x, int y)
{
int result = x + y;
return result;
}
public static int sub(int x, int y)
{
int result = x-y;
return result;
}
public static int mult(int x, int y)
{
int result = x*y;
return result;
}
public static int div(int x, int y)
{
int result = x/y;
return result;
}
}
CompareStrings with equals(..) not with ==
if (operation.equals("+")
{
System.out.println("your answer is" + (num1 + num2));
}
if (operation.equals("-"))
{
System.out.println("your answer is" + (num1 - num2));
}
if (operation.equals("/"))
{
System.out.println("your answer is" + (num1 / num2));
}
if (operation .equals( "*"))
{
System.out.println("your answer is" + (num1 * num2));
}
And the ; after the conditions was an empty statement so the conditon had no effect at all.
If you use java 7 you can also replace the if statements with a switch.
In java <7 you can test, if operation has length 1 and than make a switch for the char [switch (operation.charAt(0))]
import java.util.Scanner;
public class AdditionGame {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1;
int num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println("Please Enter The First Number");
num1 = input.nextInt();
System.out.println("Please Enter The Second Number");
num2 = input.nextInt();
Scanner op = new Scanner (System.in);
System.out.println("Please Enter The Operation");
operation = op.next();
if (operation.equals("+"))
{
System.out.println("Your Answer is "+(num1 + num2));
}
else if (operation.equals("-"))
{
System.out.println("Your Answer is "+(num1 - num2));
}
else if (operation.equals("*"))
{
System.out.println("Your Answer is "+(num1 * num2));
}
else if (operation.equals("/"))
{
System.out.println("Your Answer is "+(num1 / num2));
}
}
}
Java program example for making a simple Calculator:
import java.util.Scanner;
public class Calculator
{
public static void main(String args[])
{
float a, b, res;
char select, ch;
Scanner scan = new Scanner(System.in);
do
{
System.out.print("(1) Addition\n");
System.out.print("(2) Subtraction\n");
System.out.print("(3) Multiplication\n");
System.out.print("(4) Division\n");
System.out.print("(5) Exit\n\n");
System.out.print("Enter Your Choice : ");
choice = scan.next().charAt(0);
switch(select)
{
case '1' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a + b;
System.out.print("Result = " + res);
break;
case '2' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a - b;
System.out.print("Result = " + res);
break;
case '3' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a * b;
System.out.print("Result = " + res);
break;
case '4' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a / b;
System.out.print("Result = " + res);
break;
case '5' : System.exit(0);
break;
default : System.out.print("Wrong Choice!!!");
}
}while(choice != 5);
}
}
maybe its better using the case instead of if dunno if this eliminates the error, but its cleaner i think.. switch (operation){case +: System.out.println("your answer is" + (num1 + num2));break;case -: System.out.println("your answer is" - (num1 - num2));break; ...
import java.util.Scanner;
import javax.swing.JOptionPane;
public class javaCalculator
{
public static void main(String[] args)
{
int num1;
int num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println("please enter the first number");
num1 = input.nextInt();
System.out.println("please enter the second number");
num2 = input.nextInt();
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation");
operation = op.next();
if (operation.equals("+"))
{
System.out.println("your answer is" + (num1 + num2));
}
else if (operation.equals("-"))
{
System.out.println("your answer is" + (num1 - num2));
}
else if (operation.equals("/"))
{
System.out.println("your answer is" + (num1 / num2));
}
else if (operation.equals("*"))
{
System.out.println("your answer is" + (num1 * num2));
}
else
{
System.out.println("Wrong selection");
}
}
}
public class SwitchExample {
public static void main(String[] args) throws Exception {
System.out.println(":::::::::::::::::::::Start:::::::::::::::::::");
System.out.println("\n\n");
System.out.println("1. Addition");
System.out.println("2. Multiplication");
System.out.println("3. Substraction");
System.out.println("4. Division");
System.out.println("0. Exit");
System.out.println("\n");
System.out.println("Enter Your Choice ::::::: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int usrChoice = Integer.parseInt(str);
switch (usrChoice) {
case 1:
doAddition();
break;
case 2:
doMultiplication();
break;
case 3:
doSubstraction();
break;
case 4:
doDivision();
break;
case 0:
System.out.println("Thank you.....");
break;
default:
System.out.println("Invalid Value");
}
System.out.println(":::::::::::::::::::::End:::::::::::::::::::");
}
public static void doAddition() throws Exception {
System.out.println("******* Enter in Addition Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Addition : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Addition : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
int result = no1 + no2;
System.out.println("Addition of " + no1 + " and " + no2 + " is ::::::: " + result);
}
public static void doSubstraction() throws Exception {
System.out.println("******* Enter in Substraction Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Substraction : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Substraction : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
int result = no1 - no2;
System.out.println("Substraction of " + no1 + " and " + no2 + " is ::::::: " + result);
}
public static void doMultiplication() throws Exception {
System.out.println("******* Enter in Multiplication Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Multiplication : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Multiplication : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
int result = no1 * no2;
System.out.println("Multiplication of " + no1 + " and " + no2 + " is ::::::: " + result);
}
public static void doDivision() throws Exception {
System.out.println("******* Enter in Dividion Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Dividion : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Dividion : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
float result = no1 / no2;
System.out.println("Division of " + no1 + " and " + no2 + " is ::::::: " + result);
}
}
we can simply use in.next().charAt(0); to assign + - * / operations as characters by initializing operation as a char.
import java.util.*;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char operation;
int num1;
int num2;
System.out.println("Enter First Number");
num1 = in.nextInt();
System.out.println("Enter Operation");
operation = in.next().charAt(0);
System.out.println("Enter Second Number");
num2 = in.nextInt();
if (operation == '+')//make sure single quotes
{
System.out.println("your answer is " + (num1 + num2));
}
if (operation == '-')
{
System.out.println("your answer is " + (num1 - num2));
}
if (operation == '/')
{
System.out.println("your answer is " + (num1 / num2));
}
if (operation == '*')
{
System.out.println("your answer is " + (num1 * num2));
}
}
}
import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args) {
int x,
int y;
Scanner input=new Scanner(System.in);
System.out.println("Enter Number 1");
x=input.nextInt();
System.out.println("Enter Number 2");
y=input.nextInt();
System.out.println("Please enter operation + - / or *");
Scanner op=new Scanner(System.in);
String operation = op.next();
if (operation.equals("+")){
System.out.println("Your Answer: " + (x+y));
}
if (operation.equals("-")){
System.out.println("Your Answer: "+ (x-y));
}
if (operation.equals("/")){
System.out.println("Your Answer: "+ (x/y));
}
if (operation.equals("*")){
System.out.println("Your Answer: "+ (x*y));
}
}
}
Related
I would like to know how to do this with another way except of userinput? I don't want to write the values I want to do this the user
Calculate calculation = new Calculate();
int sum = calculation.sum(2, 5);
int testSum = 7;
#Test
public void testSum() {
System.out.println("#Test sum(): " + sum + " = " + testSum);
assertEquals(sum, testSum);
}
}
I guess the following might help:
public void test() {
int number1 = 0;
int number2 = 0;
int expected = 0;
System.out.println("Enter first number");
int state = 0;
Scanner scanner = new Scanner(System.in);
String input = "";
while(!input.equals("E")) {
input = scanner.nextLine();
input = input.toUpperCase();
if (!input.equals("") && Character.isDigit(input.charAt(0))){
switch(state) {
case 0:
number1 = Integer.parseInt(input);
System.out.println("Enter second number");
break;
case 1:
number2 = Integer.parseInt(input);
System.out.println("Enter expected result");
break;
case 2:
expected = Integer.parseInt(input);
System.out.println("Result: " + (number1 + number2) +
" | Expected: " + expected + System.lineSeparator());
System.out.println("Enter first number");
state = -1;
break;
default:
break;
}
state++;
}
}
scanner.close();
System.out.println("Exiting");
}
I'm creating a calculator where each of the calculator's functions have to be in a separate class and called from the main method using scanner input.
1.Add
2.Subtract
3.Multiplication
4.Division
5.Square
6.Power
7.Mod operation
8.Factorial
0.Quit
I must create each method called by an object. The calculator requires one main class (has main () method) and one user defined class which has above calculating methods. The program must let the user choose an operation (one of above calculations) and operand(s) (numbers). Some calculations require two operands. (e.g. A + B, AB) Some calculations require one operand. (e.g. A2, N!) Additional functions:
•Let the calculation function continues until user wants to exit this program.
•When one calculation is done, let user choose another operation.
•This program terminates when user selects END option.
•Implement all operations. Do not use Java library math methods.
I have the code for a program that is using switch statement and case, but our class hasn't even learned any of that. I have looked everywhere online for the past two days and just can't figure it out, so apologies if the solution is simple, and thank you to all help in advance. Here is the code to my program so far.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int choice;
do
{
System.out.println("[1] Add ");
System.out.println("[2] Subtract ");
System.out.println("[3] Multiply ");
System.out.println("[4] Division ");
System.out.println("[5] Square ");
System.out.println("[6] Power ");
System.out.println("[7] Mod Operation ");
System.out.println("[8] Factorial ");
System.out.println("[0] Quit ");
System.out.println("Please enter your choice: ");
choice = s.nextInt();
int num1, num2;
switch(choice)
{
case 1 : System.out.println("Enter two numbers to add: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The sum of " + num1 + " and " + num2 +
" is: " + add(num1, num2));
break;
case 2 : System.out.println("Enter two numbers to subtract: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The difference of " + num1 + " and " + num2 +
" is: " + diff(num1, num2));
break;
case 3 : System.out.println("Enter two numbers to multiply: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The product of " + num1 + " and " + num2 +
" is: " + prod(num1, num2));
break;
case 4 : System.out.println("Enter two numbers to divide: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The quotient of " + num1 + " and " + num2 +
" is: " + quo(num1, num2));
break;
case 5 : System.out.println("A number to square: ");
num1 = s.nextInt();
System.out.println("The square of " + num1 + " is: " + square(num1));
break;
case 6 : System.out.println("Enter the base and the exponent: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The power of " + num1 + " to the " + num2 +
"th power is: " + power(num1, num2));
break;
case 7 : System.out.println("Enter two numbers to get the interger remainder of (modulo): ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The modulo of " + num1 + " and " + num2 +
" is: " + mod(num1, num2));
break;
case 8 : System.out.println("Enter a number to get the factorial of: ");
num1 = s.nextInt();
System.out.println("The factorial of " + num1 + " is: " + factorial(num1));
break;
case 0: System.out.println("Thank you for using my program...good bye!");
System.exit(0);
}
}
while(choice != 0);
s.close();
}
public static int add(int num1, int num2)
{
return num1 + num2;
}
public static int diff(int num1, int num2)
{
return num1 - num2;
}
public static int prod(int num1, int num2)
{
return num1 * num2;
}
public static double quo(int num1, int num2)
{
return (double)num1 / num2;
}
public static int mod(int num1, int num2)
{
return num1 % num2;
}
public static long power(int base, int exp)
{
long result = 1;
while (exp != 0)
{
result *= base;
--exp;
}
return result;
}
public static int square(int num)
{
return num * num;
}
public static int factorial(int base)
{
if (base == 0)
return 1;
else
return(base * factorial(base - 1));
}
}
you can use a separate class called Functions with static methods
public class Functions{
public static int add(int num1, int num2)
{
return num1 + num2;
}
public static int diff(int num1, int num2)
{
return num1 - num2;
}
public static int prod(int num1, int num2)
{
return num1 * num2;
}
public static double quo(int num1, int num2)
{
return (double)num1 / num2;
}
public static int mod(int num1, int num2)
{
return num1 % num2;
}
public static long power(int base, int exp)
{
long result = 1;
while (exp != 0)
{
result *= base;
--exp;
}
return result;
}
public static int square(int num)
{
return num * num;
}
public static int factorial(int base)
{
if (base == 0)
return 1;
else
return(base * factorial(base - 1));
}
}
and you call these methods Functions.add(num1, num2))
I'm not sure if that what you want
Here is an approach, which may be useful to you. I have done implementation for Addition and Subtraction, you can follow the same thing for other operations as well. You may want to have abstract class for single operand operations as well.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int choice;
do {
System.out.println("[1] Add ");
System.out.println("[2] Subtract ");
System.out.println("[3] Multiply ");
System.out.println("[4] Division ");
System.out.println("[5] Square ");
System.out.println("[6] Power ");
System.out.println("[7] Mod Operation ");
System.out.println("[8] Factorial ");
System.out.println("[0] Quit ");
System.out.println("Please enter your choice: ");
choice = s.nextInt();
int num1, num2;
switch (choice) {
case 1:
Addition addition = new Addition(s);
addition.performOperation();
break;
case 2:
Subtraction subtraction = new Subtraction(s);
subtraction.performOperation();
break;
case 3:
System.out.println("Enter two numbers to multiply: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The product of " + num1 + " and " + num2 +
" is: " + prod(num1, num2));
break;
case 4:
System.out.println("Enter two numbers to divide: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The quotient of " + num1 + " and " + num2 +
" is: " + quo(num1, num2));
break;
case 5:
System.out.println("A number to square: ");
num1 = s.nextInt();
System.out.println("The square of " + num1 + " is: " + square(num1));
break;
case 6:
System.out.println("Enter the base and the exponent: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The power of " + num1 + " to the " + num2 +
"th power is: " + power(num1, num2));
break;
case 7:
System.out.println("Enter two numbers to get the interger remainder of (modulo): ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The modulo of " + num1 + " and " + num2 +
" is: " + mod(num1, num2));
break;
case 8:
System.out.println("Enter a number to get the factorial of: ");
num1 = s.nextInt();
System.out.println("The factorial of " + num1 + " is: " + factorial(num1));
break;
default:
System.out.println("Your choices should be 0 to 8!");
break;
}
}
while (choice != 0);
s.close();
System.out.println("Thank you for using my program...good bye!");
System.exit(0);
}
public static int prod(int num1, int num2) {
return num1 * num2;
}
public static double quo(int num1, int num2) {
return (double) num1 / num2;
}
public static int mod(int num1, int num2) {
return num1 % num2;
}
public static long power(int base, int exp) {
long result = 1;
while (exp != 0) {
result *= base;
--exp;
}
return result;
}
public static int square(int num) {
return num * num;
}
public static int factorial(int base) {
if (base == 0)
return 1;
else
return (base * factorial(base - 1));
}
}
abstract class OperationWithTwoOperands {
protected String prompt;
private Scanner scanner;
public OperationWithTwoOperands(Scanner scanner) {
this.scanner = scanner;
}
public void performOperation() {
System.out.println(prompt);
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
operation(num1, num2);
}
abstract protected void operation(int operand1, int operand2);
}
class Addition extends OperationWithTwoOperands {
public Addition(Scanner scanner) {
super(scanner);
prompt = "Enter two numbers to add:";
}
#Override
protected void operation(int num1, int num2) {
System.out.println("The sum of " + num1 + " and " + num2 + " is: " + (num1 + num2));
}
}
class Subtraction extends OperationWithTwoOperands {
public Subtraction(Scanner scanner) {
super(scanner);
prompt = "Enter two numbers to subtract:";
}
#Override
protected void operation(int num1, int num2) {
System.out.println("The difference of " + num1 + " and " + num2 + " is: " + (num1 - num2));
}
}
Here is a copy of my code,
i expected to save the results of the below code into a csv, and also ask the user do you want to review the results? if yes then display the contents of csv saved.
import java.io.*;
import java.util.Scanner;
public class TestMathOP {
public static void main(String [] args) {
float num1;
float num2;
Scanner input = new Scanner (System.in);
char choice;
do
{
System.out.print ("Enter the first number:");
num1 = input.nextFloat();
System.out.print ("Enter the second number:");
num2 = input.nextFloat();
System.out.println();
System.out.println("The sum of the numbers is " + (num1 + num2));
System.out.println("The subtract of the two numbers is " + + (num1 - num2));
System.out.print("Do you want to exit? Y/N ");
choice = input.next().charAt(0);
}
while ((choice == 'n') || (choice == 'n'));
System.out.print("Thanks for using our system");
if ((choice == 'y') || (choice == 'y'));
}
}
This should work. I think like #AlexZam said, try to go step by step.
public static void main(String[]args) throws IOException{
//creates file
File file = new File("file.csv");
//Change to strings
String num1;
String num2;
Scanner input = new Scanner (System.in);
//your choice
boolean isNo = false;
boolean isYes = false;
do
{
//enables writing to file
FileWriter fileWriter = new FileWriter("file.csv");
Scanner scanner = new Scanner(file);
System.out.print ("Enter the first number:");
float calc1;
calc1 = input.nextFloat();
String firstNumber = calc1 + "";
//WRITES TO FILE
fileWriter.write(firstNumber+"\n");
System.out.print ("Enter the second number:");
float calc2;
calc2 = input.nextFloat();
String secondNumber = calc2+"";
//WRITES TO FILE
fileWriter.write(secondNumber +"\n");
String message = "The sum of the numbers is " + (calc1 + calc2) + "\nThe subtract of the two numbers is " + (calc1 - calc2);
System.out.println(message);
fileWriter.write(message);
//close filewriting
fileWriter.close();
String question = ("Do you want to exit? Y/N ");
System.out.print(question);
String answer = input.next();
if(answer.equals("y")) {
isYes = true;
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
}else if(answer.equals("n")) {
isNo = true;
System.out.println("Thanks for using our systems!");
}
} while (!isNo&&!isYes);
}
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
Recently I started programming in java so I don't know too much but I need some help. I wrote a calculator (if you can even call it that...) there isn't a gui or anything yet but I wanted to revise my code into a loop so it would take the users first number, second number and what they wanted to do (add subtract ect) and solve it and then re-loop so it would do it again. I tried a do-while loop but I couldn't get it to work.
import java.util.Scanner;
public class Calculator {
public static void main(String [] args){
Scanner in=new Scanner(System.in);
long sum = 0;
long num1 = 0;
long num2 = 0;
char s=' ';
String answer="yes";
border();
System.out.println("Acara's Calculator™ V_.01");
border();
System.out.println("What is your first number? ");
num1=in.nextInt();
System.out.println("What is your second number? ");
num2=in.nextInt();
System.out.println("What operation would you like to do?");
System.out.println("Press '+' for addition, '-' for subtraction, '/' for division or '*' for multiplication.");
s=in.next().charAt(0);
if (s=='/'){
sum=num1/num2;
System.out.println("Your answer is : " + sum);
}
else if (s=='*'){
sum=num1*num2;
System.out.println("Your answer is : " + sum);
}
else if (s=='+'){
sum=num1+num2;
System.out.println("Your answer is : " + sum);
}
else if (s=='-'){
sum=num1-num2;
System.out.println("Your answer is : " + sum);
}
border();
}
public static void border(){
System.out.println("***** ***** ***** ***** ***** ***** ***** ***** ***** *****");
}
}
Try this
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long sum = 0;
long num1 = 0;
long num2 = 0;
char s = ' ';
String answer = "yes";
while (true) {
border();
System.out.println("Acara's Calculator™ V_.01");
System.out.println("What operation would you like to do?");
System.out.println("Press '+' for addition, '-' for subtraction, '/' for division or '*' for multiplication and 'q' for quit.");
s = in.next().charAt(0);
if (s == 'q') {
break;
}
border();
System.out.println("What is your first number? ");
num1 = in.nextInt();
System.out.println("What is your second number? ");
num2 = in.nextInt();
if (s == '/') {
sum = num1 / num2;
System.out.println("Your answer is : " + sum);
} else if (s == '*') {
sum = num1 * num2;
System.out.println("Your answer is : " + sum);
} else if (s == '+') {
sum = num1 + num2;
System.out.println("Your answer is : " + sum);
} else if (s == '-') {
sum = num1 - num2;
System.out.println("Your answer is : " + sum);
}
border();
}
}
public static void border() {
System.out.println("***** ***** ***** ***** ***** ***** ***** ***** ***** *****");
}
}
Here is the kind of loop you needed.
import java.util.Scanner;
public class Calculator {
public static void main(String [] args){
Scanner in=new Scanner(System.in);
long result = 0;
long num1 = 0;
long num2 = 0;
char s=' ';
String token = "";
border();
System.out.println("Acara's Calculator™ V_.01");
border();
while (true){
System.out.println("What is your first number? ... Or press ! to quit.");
token = in.next();
if ("!".equalsIgnoreCase(token.trim())){
break;
}
num1 = Integer.parseInt(token);
System.out.println("What is your second number? ... Or press ! to quit.");
token = in.next();
if ("!".equalsIgnoreCase(token.trim())){
break;
}
num2 = Integer.parseInt(token);
System.out.println("What operation would you like to do?");
System.out.println("Press '+' for addition, '-' for subtraction, '/' for division " +
"or '*' for multiplication... Or press ! if you want to quit.");
token = in.next();
if ("!".equalsIgnoreCase(token.trim())){
break;
}
s=token.trim().charAt(0);
if (s=='/'){
result=num1/num2;
System.out.println("Your answer is : " + result);
}
else if (s=='*'){
result=num1*num2;
System.out.println("Your answer is : " + result);
}
else if (s=='+'){
result=num1+num2;
System.out.println("Your answer is : " + result);
}
else if (s=='-'){
result=num1-num2;
System.out.println("Your answer is : " + result);
}
border();
}
}
public static void border() {
System.out
.println("***** ***** ***** ***** ***** ***** ***** ***** ***** *****");
}
}
This is probably what you want - it encloses your code in a while loop, but does so without making one huge main() function:
import java.util.Scanner;
public class Calculator {
private static final Scanner in = new Scanner(System.in);
public static void main(String [] args){
singleLoop();
while(shouldContinue()) {
singleLoop();
}
}
private static boolean shouldContinue() {
System.out.println("Run again? (yes/no)");
return (in.next().equalsIgnoreCase("yes"));
}
private static void singleLoop() {
long sum = 0;
long num1 = 0;
long num2 = 0;
char s=' ';
String answer="yes";
border();
System.out.println("Acara's Calculator™ V_.01");
border();
System.out.println("What is your first number? ");
num1=in.nextInt();
System.out.println("What is your second number? ");
num2=in.nextInt();
System.out.println("What operation would you like to do?");
System.out.println("Press '+' for addition, '-' for subtraction, '/' for division or '*' for multiplication.");
s=in.next().charAt(0);
if (s=='/'){
sum=num1/num2;
System.out.println("Your answer is : " + sum);
}
else if (s=='*'){
sum=num1*num2;
System.out.println("Your answer is : " + sum);
}
else if (s=='+'){
sum=num1+num2;
System.out.println("Your answer is : " + sum);
}
else if (s=='-'){
sum=num1-num2;
System.out.println("Your answer is : " + sum);
}
border();
}
public static void border(){
System.out.println("***** ***** ***** ***** ***** ***** ***** ***** ***** *****");
}
}