Trouble with basic calculator using switch - java

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

Related

Another way except of UserInput

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");
}

Switch statement Errors Exception in thread "main" java.util.NoSuchElementException: No line found

I think the problem is with the switch statement, I keep getting errors in the grade when the grader tries to input 'q.' But no errors in the IDE. error
error2
switch (chV)
{
case 'q':
System.exit(0);
break;
case 'c':
int cntNonWhitespaces = getNumOfNonWSCharacters(textInput);
System.out.print("Number of non-whitespace characters: " + cntNonWhitespaces);
break;
case 'w':
int wordsCount = getNumOfWords(textInput);
System.out.println("Number of words: " + wordsCount);
break;
case 'f':
System.out.println("Enter a word or phrase to be found: ");
String findS = scannerInput.nextLine();
int findCount = findText(textInput, findS);
System.out.println("\"" + findS + "\""+ " " + "instances: " + findCount);
break;
case 'r':
String newstringVal = replaceExclamation(textInput);
System.out.println("Edited textInput: " + newstringVal);
break;
case 's':
newstringVal = shortenSpace(textInput);
System.out.println("Edited textInput:" + newstringVal);
break;
default:
System.out.println("Invalid option. Please try again");
}
Ill attach the errors I keep getting
Full Code:
import java.util.*;
public class AuthoringAssistant {
public static Scanner scannerInput = new Scanner(System.in);
public static String shortenSpace(String textInput) {
String tempVal = textInput.trim().replaceAll(" +", " ");
return tempVal;
}
public static String replaceExclamation(String textInput) {
String tempVal = textInput.replaceAll("!", ".");
return tempVal;
}
public static int findText(String textInput, String findS) {
int countVal = 0;
int it = 0;
while ((it = textInput.indexOf(findS)) != -1) {
textInput = textInput.substring(it +
findS.length());
countVal += 1;
}
return countVal;
}
public static int getNumOfWords(String textInput) {
textInput = shortenSpace(textInput);
String[] words1 = textInput.split(" ");
return words1.length;
}
public static int getNumOfNonWSCharacters(String textInput) {
textInput = textInput.trim().replaceAll("\\s", "");
return textInput.length();
}
public static void printMenu() {
System.out.println("MENU");
System.out.println("c - Number of non-whitespace characters");
System.out.println("w - Number of words");
System.out.println("f - Find text");
System.out.println("r - Replace all !'s");
System.out.println("s - Shorten spaces");
System.out.println("q - Quit");
System.out.println("");
System.out.println("Choose an option:");
}
public static void main(String[] args) {
while(true)
{
System.out.println("Enter a sample text:");
System.out.println("");
String textInput = scannerInput.nextLine();
System.out.print("You entered: " + textInput);
System.out.println("");
System.out.println("");
printMenu();
char chV = scannerInput.nextLine().charAt(0);
switch (chV)
{
case 'q':
System.exit(0);
break;
case 'c':
int cntNonWhitespaces = getNumOfNonWSCharacters(textInput);
System.out.print("Number of non-whitespace characters: " + cntNonWhitespaces);
break;
case 'w':
int wordsCount = getNumOfWords(textInput);
System.out.println("Number of words: " + wordsCount);
break;
case 'f':
System.out.println("Enter a word or phrase to be found: ");
String findS = scannerInput.nextLine();
int findCount = findText(textInput, findS);
System.out.println("\"" + findS + "\""+ " " + "instances: " + findCount);
break;
case 'r':
String newstringVal = replaceExclamation(textInput);
System.out.println("Edited textInput: " + newstringVal);
break;
case 's':
newstringVal = shortenSpace(textInput);
System.out.println("Edited textInput:" + newstringVal);
break;
default:
System.out.println("Invalid option. Please try again");
}
System.out.println();
}
}
}

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

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....

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';
}
}
}

Basic calculator in Java

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));
}
}
}

Categories

Resources