Basic Java Calcualtor: Only addition working [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am trying to build a simple calculator that operates on Double values and performs:
+
-
*
/
negation
^2
for some reason, whichever operation i specify when running the program executes the addition function. So when I try to do
5
7
*
I get 12.0 and not 35.
Any suggestions?
I would also really like some help implementing a way to quit this program when the word "exit" is entered. I was thinking something like System.exit(0);
but Im not sure how to implement. this is my code so far:
import java.util.Scanner;
public class Calc {
public static void main(String[] args)
{
double num1;
double num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println ("Enter 'exit' to quit the calculator or 'help' for more options");
System.out.println("Enter the first number:");
num1 = input.nextInt();
System.out.println ("Display:" + num1);
System.out.println("Enter the second number:");
num2 = input.nextInt();
System.out.println ("Display:" + num2);
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation:");
operation = op.next();
if (operation == "+");
{
System.out.println((num1 + num2));
}
if (operation == "-"){
{
System.out.println((num1 - num2));
}
if (operation == "/"){
{
System.out.println((num1 / num2));
}
if (operation == "*"){
{
System.out.println((num1 * num2));
}
}
}

there is a semicolon at if (operation.equals("+"));
so, System.out.println((num1 + num2)); will always work
And also replace, == with .equals("+")
as == checks for reference, while equals checks for the value of the variable.

please change operation == to operation.equals("your value")

There are at least three main issues with your code...
Firstly, String comparison in Java is done using .equals not ==
Secondly...
if (operation == "+");
Has a semi-colon at the end, which basically means that even if the condition is meet, it will not run anything, but will skip to the next execution block, which is ...
{
System.out.println((num1 + num2));
}
Thirdly, you have an extra open brace ({) here...
if (operation == "-"){
{
Here...
if (operation == "/"){
{
And here...
if (operation == "*"){
{
Which is going to completely screw up your logic
You should also make use of else-if blocks as well...
Instead, try something like...
if ("+".equals(operation))//;
{
System.out.println((num1 + num2));
}
else if ("-".equals(operation)) //{
{
System.out.println((num1 - num2));
}
else if ("/".equals(operation)) //{
{
System.out.println((num1 / num2));
}
else if ("*".equals(operation)) //{
{
System.out.println((num1 * num2));
}
I've commented out the problem areas so you can see where they exists before hand

try this way
Instead of using == use .equals()
import java.util.Scanner;
public class Calc {
public static void main(String[] args)
{
double num1;
double num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println ("Enter 'exit' to quit the calculator or 'help' for more options");
System.out.println("Enter the first number:");
num1 = input.nextInt();
System.out.println ("Display:" + num1);
System.out.println("Enter the second number:");
num2 = input.nextInt();
System.out.println ("Display:" + num2);
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation:");
operation = op.next();
if (operation.equals("+"))
{
System.out.println((num1 + num2));
}
if (operation.equals("-"))
{
System.out.println((num1 - num2));
}
if (operation.equals("/")){
{
System.out.println((num1 / num2));
}
if (operation.equals( "*")){
{
System.out.println((num1 * num2));
}
}
}

Related

Beginner Java calculator - How to ignore a string being entered instead of crashing the code? [duplicate]

This question already has answers here:
In Java, how do I check if input is a number?
(4 answers)
Closed 5 years ago.
Is there a basic solution I am missing here?
Side note, I don't particularly want a super advanced solution as I am in the first 8 weeks of a computer science course in college and I feel it is either something simple I am missing or something I haven't learned yet.
Please focus on what I am asking, I know the code can be cleaner for now I don't want tips on how to make it more efficient I know there is too much repetition.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
/*Initializing a string which will be
*used in the future to determine the
*operator the user wants to use*/
String operator = "z"; //Cant be A,S,M or D or the program would skip my while loop
//Creating number variables which will initilised later by user input//
int numOne;
int numTwo;
//Creating a boolean variable asking the user if they would like
//to run another calculation and a String to store Yes or No
boolean anotherCalc = true;
String runAgain = "p";
Scanner userOperator = new Scanner(System.in);
Scanner userNumbers = new Scanner(System.in);
Scanner userAgain = new Scanner(System.in);
while (anotherCalc == true) { //Containing the whole calculator in this while loop
//so it only stops when the user says they don't want another calc
while (!operator.equalsIgnoreCase("A") && !operator.equalsIgnoreCase("S")
&& !operator.equalsIgnoreCase("M") && !operator.equalsIgnoreCase("D")
&& operator.equalsIgnoreCase("z")){
System.out.println("What kind of calculation would you like to make?");
System.out.println("Press A for Addition\nPress S for Substraction");
System.out.println("Press M for Multiplication\nPress D for Division");
operator = userOperator.next();
}
System.out.println("\nThank you, now what numbers would you like to use?");
System.out.println("Enter number 1:");
String numError;
numError = userNumbers.next();
numOne = Integer.parseInt(numError);
System.out.println("Enter number 2:");
String numError2;
numError2 = userNumbers.next();
numTwo = Integer.parseInt(numError2);
int answer;
//Starting outer if statement containing nested if statements for
//all 4 operators
//Addition if statement with nested if statement that won't
//break the code if someone trys to add outside the int value range
if (operator.equalsIgnoreCase("A")){
if (numOne > 1073741824 || numTwo > 1073741824){
long answerlong = (long) numOne + (long) numTwo;
System.out.print("\nYour answer is " + answerlong);
} else {answer = numOne + numTwo;
System.out.println("\nYour answer is " + answer);}
//Subtraction if statement with nested if statement that won't
//break the code if someone trys to subtract from a number above the int value range
} else if (operator.equalsIgnoreCase("S")){
if (numOne > 2147483647 || numTwo > 2147483647){
long answerlong = (long) numOne - (long) numTwo;
System.out.print("\nYour answer is " + answerlong);
} else {
answer = numOne - numTwo;
System.out.println("\nYour answer is " + answer);
}
} else if (operator.equalsIgnoreCase("M")){
if (numOne > 20000 || numTwo > 20000){
long answerlong = (long) numOne * (long) numTwo;
System.out.print("\nYour answer is " + answerlong);
} else {
answer = numOne * numTwo;
System.out.println("\nYour answer is " + answer);
}
} else if (operator.equalsIgnoreCase("D")){
if (numOne % numTwo == 0){ //Nested if else statement so
answer = numOne / numTwo; //an answer with no decimal
System.out.println("\nYour answer is " + answer); //point is shown as a whole
//number and otherwise return decimals
} else {
float answerdec = (float) numOne / (float) numTwo;
System.out.printf("\nYour answer is " + "%.2f",answerdec);}
} else {
System.out.println("\nError");
}
System.out.println("\nWould you like to run another calculation?");
System.out.println("Press Y for Yes or N for No");
runAgain = userAgain.next();
if (runAgain.equalsIgnoreCase("Y")){
anotherCalc = true;
operator = "z"; //This needs to be added so it returns to ask the user what type of calculation
System.out.println("\n\n"); //This is just for aesthetics, creating 2 lines before the program runs again. Not included on the first run of the program on purpose.
} else if (runAgain.equalsIgnoreCase("N")){
anotherCalc = false;
} else {
anotherCalc = false;
System.out.println("\n\nInput Error (Y or N not entered)\nPlease reload the program");
}
}
System.out.println("\n\nThank you for using the calculator");
System.out.println("I hope you enjoyed it");
parseInt() will throw NumberFormatException, so it should be caught... so for example:
try{
numOne = Integer.parseInt(numError);
}catch(NumberFormatException nfe){
System.out.println("Error: value entered is not a number");
System.out.println("Please try again");
continue;
}

A simple console calculator

I have designed a simple console calculator as follows but i need to create a loop where I can re run the program:
So that I won't need to run the program again and again and it can take the input from the user and run by itself.
private static Scanner op;
private static Scanner input;
private static Scanner cont;
public static void main(String args[]) {
double num1;
double num2;
double ans = 0;
double l1;
double l2;
String operation;
input = new Scanner(System.in);
System.out.println("Please input your first number:");
num1= input.nextDouble();
System.out.println("Please input the second numer:");
num2= input.nextDouble();
op = new Scanner(System.in);
System.out.println("Select your operation:");
operation = op.next();
if (operation.equals("+")){
System.out.println("Your Result is :" + (num1+num2));
}
if (operation.equals("-")){
System.out.println("Your Result is:" + (num1-num2));
}
if (operation.equals("/")){
if (num2 == 0){
System.out.println("Your Input is Invalid");}
else {
System.out.println("Your result is :" + (num1/num2));
}
}
if (operation.equals("*")){
System.out.println("Your result is:" + (num1*num2));
}
if (operation.equals("%")){
System.out.println("Your result is:" + (num1*100/num2));
}
if (operation.equals("^")){
ans= Math.pow(num1, num2);
System.out.println("Your result is:"+ans);
}
if (operation.equals("log")){
l1=Math.log(num1);
l2=Math.log(num2);
System.out.println("Your result is:"+l1/l2);
}
operation = cont.next();
System.out.println("Do you wish to perform any other operation?");
if (operation.equals("Yes")){
else{
System.out.println("Thank You");
}
}
}
you can create a function and call it with a loop like this:
private static void myfunction(){
//put your code here
}
public static void main(String[] args) {
//call your function until your condition is false
while(myconditionistrue){
myfunction();
}
}
if you want to ask your user if continue or not use this way:
private static void myfunction() {
//put your code here
}
public static void main(String[] args) {
String exit;
Scanner scan = new Scanner(System.in);
do {
//call your function or you can put all your code here
myfunction();
System.out.println("You want to continue? y : n :");
exit = scan.next();
} while (exit.equals("y"));
}
You can use a while(true) and then just exit at command:
import java.util.Scanner;
class Main {
private static Scanner op;
private static Scanner input;
private static Scanner cont;
public static void main(String args[]) {
double num1;
double num2;
double ans = 0;
double l1;
double l2;
String operation;
while (true) {
input = new Scanner(System.in);
System.out.println("Please input your first number:");
num1 = input.nextDouble();
System.out.println("Please input the second numer:");
num2 = input.nextDouble();
op = new Scanner(System.in);
System.out.println("Select your operation:");
operation = op.next();
if (operation.equals("+")) {
System.out.println("Your Result is :" + (num1 + num2));
}
if (operation.equals("-")) {
System.out.println("Your Result is:" + (num1 - num2));
}
if (operation.equals("/")) {
if (num2 == 0) {
System.out.println("Your Input is Invalid");
} else {
System.out.println("Your result is :" + (num1 / num2));
}
;
}
if (operation.equals("*")) {
System.out.println("Your result is:" + (num1 * num2));
}
if (operation.equals("%")) {
System.out.println("Your result is:" + (num1 * 100 / num2));
}
if (operation.equals("^")) {
ans = Math.pow(num1, num2);
System.out.println("Your result is:" + ans);
}
if (operation.equals("log")) {
l1 = Math.log(num1);
l2 = Math.log(num2);
System.out.println("Your result is:" + l1 / l2);
}
//cont = new Scanner(System.in);
//operation = cont.next();
System.out.println("Do you wish to perform any other operation?");
cont = new Scanner(System.in);
operation = cont.next();
if (operation.equals("Yes")) {
} else {
System.out.println("Thank You");
System.exit(0);
}
}
}
}
Test
Please input your first number:
5
Please input the second numer:
5
Select your operation:
*
Your result is:25.0
Do you wish to perform any other operation?
Yes
Please input your first number:
20
Please input the second numer:
10
Select your operation:
+
Your Result is :30.0
Do you wish to perform any other operation?
No
Thank You
As RealSkeptic stated in his comment, what you need is a loop. You can learn about loops, for example, here. The best choice for this situation is do-while loop.
I have a few more advices to your code:
You don't need to create many scanners to get more inputs than just one. One instance suffices.
When you use many if statements whose conditions are disjoint (by that I mean that if a single condition is true then the rest of the conditions is false), use else-if statements. It is more efficient. See this for more information.
Don't use empty branches in if statement. In this particular example, you can use if (!operation.equals("Yes")). The exclamation mark means negation. So if operation equals "Yes", the whole condition is evaluated as false.
Learn how to divide a complex code into functions (or methods). Generally, one function should provide one simple functionality.

how to scan for certain character with scanner(system.in)

I'm new to java programming. I tried to make calculator that can do 4 basic math operations using if statement. However I don't have it working as expected. When trying to parse operator, it just finishes with else statement.
I guess I have not properly formatted if statement ?
Any help is greatly appreciated.
Thanks.
import java.util.Scanner;
import java.lang.Object;
public class calc {
public static void main(String args[]) {
System.out.println("Test kalkulator za sabiranje");
Scanner keyboard = new Scanner(System.in);
double fnum, snum, res;
String ch = "";
System.out.println("Enter first number: ");
fnum = keyboard.nextDouble();
System.out.println("Enter operation: ");
ch = keyboard.next();
if( ch == "+") {
System.out.println("Enter second number: ");
snum = keyboard.nextDouble();
res = fnum + snum;
System.out.println("Result is: "+ res);
}
else if ( ch == "-") {
System.out.println("Enter second number: ");
snum = keyboard.nextDouble();
res = fnum - snum;
System.out.println("Result is: "+ res);
}
else if ( ch == "/") {
System.out.println("Enter second number: ");
snum = keyboard.nextDouble();
res = fnum / snum;
System.out.println("Result is: "+ res);
}
else if( ch == "*") {
System.out.println("Enter second number: ");
snum = keyboard.nextDouble();
res = fnum * snum;
System.out.println("Result is: "+ res);
}
else {
System.out.println("You entered wrong operator, please try again");
}
keyboard.close();
}
}
String objects are reference objects, meaning when you type out code like
str == "+"
you're checking to see if the point in memory where str is located is equal to +. To verify if two strings equate each other, you need to use the method .equals like so
str.equals("+")
instead of == you should use equals method
Your code is fine, the problem is when you compare ch with the strings "+","-", and so on...
In java strings are Objects. Comparing objects with the == operator would only return true if the objects referrring to the same object. In order to actually compare the two objects you need to use the equals() method.
So to sum up, the correct conditions should be:
if(ch.equals("+")){ }
for every comparison.

Can someone figure out whats wrong with my code?

I've run a debugger and everything, but I can't find out whats wrong! I run the code, and it accepts a as an asnwer, but if i put b, it runs the code saying "This is not an A or a B"
import java.util.Scanner;
public class messingAround {
public static void main(String[] args){
Scanner ques = new Scanner(System.in);
String question;
System.out.println("Would you like to:");
System.out.println("A: Solve a math problem");
System.out.println("B: Display Pi");
System.out.println("Type A or B (no caps)");
question = ques.next();
if(!(question.equals("a")) || question.equals("b")){
System.out.println("Sorry that isn't an A or a B");
System.out.println("Try running the code again");
}else if(question.equals("a")) {
double fnum, snum, answer;
String type;
Scanner intString = new Scanner(System.in);
System.out.println("Enter your first number: ");
fnum = intString.nextDouble();
System.out.println("Enter your second number: ");
snum = intString.nextDouble();
System.out.println("What would you like to do? (+ - * /)");
type = intString.next();
if(type.equals("*")){
answer = fnum * snum;
System.out.println("The product is: " + answer);
}else if(type.equals("+")) {
answer = fnum + snum;
System.out.println("The sum is: " + answer);
}else if(type.equals("-")) {
answer = fnum - snum;
System.out.println("The difference is: " + answer);
}else if(type.equals("/")) {
answer = fnum / snum;
System.out.println("The dividend is: " + answer);
}
}else if(question.equals("b")) {
System.out.println("3.14159265359");
}
}
}
if(!(question.equals("a")) || question.equals("b")){
parens are a bit off. Try this:
if(!(question.equals("a") || question.equals("b"))){

Exiting a program with System.exit(0) in java

I am a little confused about how to implement System.exit(0); in my program. What I want to have happen is for the user to type the word "exit" and for the program to terminate. I would also like the program to return "0.0" when "clear" is entered, but I think I am having trouble working with my variables because num1 and num2 are doubles but I want "exit" and "clear" to be acceptable inputs, as well.
If anyone has any insight, that would be greatly appreciated. Here is my code:
package projectapcs;
/**
*
* #author Apple
*/
import java.util.Scanner;
public class ProjectAPCS {
public static void exit(int x){
}
public static void clear(int y){
}
public static void main(String[] args) {
double num1;
double num2;
char char1;
String operation;
Scanner input = new Scanner(System.in);
System.out.println
("Enter 'exit' to quit the calculator, 'help' for more options or 'continue' to use the calculator");
System.out.println
("\nEnter the first number:");
num1 = input.nextInt();
System.out.println
("Display:" + num1);
System.out.println("Please enter operation:");
operation = input.next();
System.out.println("Enter the second number:");
num2 = input.nextInt();
System.out.println ("Display:" + num2);
if ("+".equals(operation)){
System.out.println((num1 + num2));
}
else if ("-".equals(operation)){
System.out.println((num1 - num2));
}
else if ("/".equals(operation)){
System.out.println((num1 / num2));
}
else if ("*".equals(operation)){
System.out.println((num1 * num2));
}
else if ("-x".equals(operation)){
System.out.println (-num1);
}
else if ("x^2".equals(operation)){
System.out.println (num1 * num1);
}
else if ("sqrt".equals(operation)){
System.out.println (Math.sqrt(num1));
}
else if ("H".equals(num1)){
System.out.println("Type + for the addition of values");
System.out.println("Type - for the substraction of values");
System.out.println("Type * for the multiplcation of values");
System.out.println("Type / for the division of values");
System.out.println("Type negate for the negation of values");
System.out.println("Type ^2 for squaring of values");
}
else if("E".equals(num1)){
System.out.println ("Calculator program terminated...");
System.exit(0);
}
}
}
If you want to allow arbitrary inputs, read input as a String, then convert to double as needed:
String input = scanner.next();
if (input.equals("exit")) {
exit();
else if (input.equals("clear")) {
clear();
} else {
try {
double number = Double.parseDouble(input);
/* do something with `number` */
} catch (NumberFormatException e) {
System.err.println("Not a double.");
}
}

Categories