Jump to content

Need help with simple java calculator

TacticTerror

Hi everyone, I am just creating a simple java calculator and I have a problem with something. I have another class as you will see but it is working fine so don't mind the call for it. My problem is that whenever I enter the operator and my two doubles, the answer is always 1. Can anyone explain why this is? Thanks in advance.

 

 

 

import java.util.Scanner;
 
public class Calculate {
public static void main(String args[]){
 
@SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
double num1, num2, answer;
String operate;
End endObject = new End();
endObject.statement();
try {
Thread.sleep(500);
} catch (InterruptedException e){}
System.out.println("Please select your operator");
operate = scan.nextLine();
System.out.println("Enter first value");
num1 = scan.nextDouble();
System.out.println("Enter second value");
num2 = scan.nextDouble();
while (operate == "+")
answer = num1 + num2;
while (operate == "-");
answer = num1 - num2;
while (operate == "*");
answer = num1 * num2;
while (operate == "/");
answer = num1 / num2;
System.out.println("Your answer is...");
System.out.println(answer);
try {
Thread.sleep(1000);
} catch (InterruptedException e){}
@SuppressWarnings("resource")
Scanner scan2 = new Scanner(System.in);
System.out.println("Would  you like to clear?");
System.out.println("Type yes or no.");
String sentence = scan2.nextLine();
if (sentence.contains("yes"))
main (args);
if (sentence.contains("no"))
endObject.finalmessage();
}
 
 
}
 
Link to comment
Share on other sites

Link to post
Share on other sites

1st: please use the code tags (symbol <> in the editor)

2nd: Are you sure you want to use whiles in the operations? (Rhetorical; you do not!)

3rd: main recursion?! No.

4th: No need for different scanners.

Link to comment
Share on other sites

Link to post
Share on other sites

should I use If statement?

Alternative to main recursion?

I will remove scanner :)

Link to comment
Share on other sites

Link to post
Share on other sites

Yes, the if statement is more adequate, since you want to perform an action depending on the operator and not keep performing it while the operator is that one.

Instead of using recursion you could have a while cycle that checked a variable (boolean, for instance) and, while that variable is true you'd perform the reads and operations. At the end, in your if(sentence.contains("no")) you'd set that variable to false to end the cycle.

Link to comment
Share on other sites

Link to post
Share on other sites

What @MikeD said, please use the code tag next time....it is near impossible to read otherwise.

 

Your main problem right now (why you always receive 1) is your operate == will be false use operator.equals()

e.g.

int test() {	string test = "123";	test += "4";	if(test == "1234")		return 1; //This will never be returned, it compares the location of test not the value	else if(test.equals("1234"))		return 2; //This will compare the value so it will always be returned	return 3;  //Well this won't be hit, but it doesn't matter}

Also using main for your work is not a wise idea...doing a recursive function in main is a never do type of thing.

If you want to remove that recursive portion at the very least just create a new function.

 

eg. void calculate()...but given the user can keep continuing I wouldn't recommend recursion at all (you will eat up all the stack and get an error if the user keeps inputting values)

 

The better way is have calculate ask for the numbers and operators and then in your main function just have a while loop asking to continue

//This won't compile and doesn't have all the correct syntax, just used to illustrate the wayvoid main(..) {do{    calculate();} while(wantsToContinue());}bool wantsToContinue() {    print 'Do you want to continue (y/n)'    return (scan.nextLine().equals("y"));}void calculate() {//Do your stuff here}

0b10111010 10101101 11110000 00001101

Link to comment
Share on other sites

Link to post
Share on other sites

On a side not that actually annoys me about java(amungs many other things) the whole == vs .equals, the compiler should be smart enough to interpret and optimise that as .net has done for years. there is almost no real world value in comparing pointers for strings...

Link to comment
Share on other sites

Link to post
Share on other sites

New question, I would like to make a statement controlled by a value and I don't know how I would go about doing this while not resetting the value of my counter on re-initiation of the statement.

public void statement(){		int num = 0;			if (num == 0)				System.out.println("This program is a simple calculator");			if (num < 0)				System.out.println(" ");		num = 1;			}	}
Link to comment
Share on other sites

Link to post
Share on other sites

 

New question, I would like to make a statement controlled by a value and I don't know how I would go about doing this while not resetting the value of my counter on re-initiation of the statement.

public void statement(){		int num = 0;			if (num == 0)				System.out.println("This program is a simple calculator");			if (num < 0)				System.out.println(" ");		num = 1;			}	}

I'm guessing what you want to do is remember that you have already displayed the message...

You could make num be an object variable. That way, each time the method is called in that instance the value is the same.

Link to comment
Share on other sites

Link to post
Share on other sites

how would I make the num an object variable? example?

public class Foo {  int num = 0;  ...  public void statement() {    if(num == 0) {      System.out.println("...");      num = 1;    }  }}    

I'm not sure this is what you're trying to do though.

Link to comment
Share on other sites

Link to post
Share on other sites

I am trying to make a program that after it's first execution, will no longer display the statement.

Link to comment
Share on other sites

Link to post
Share on other sites

Is this correct, because it doesn't seem to work. It still resets runs to (0) on next pass-through and displays the message.

public class State {	int runs = 0;public void statement(){		if (runs == 0)			System.out.println("This program is a simple calculator");		if (runs < 0)			System.out.println(" ");	runs = 1;		}}
Link to comment
Share on other sites

Link to post
Share on other sites

If it helps, this is my whole program.

import java.util.Scanner;public class Calculate {	public static void main(String args[]){				@SuppressWarnings("resource")		Scanner scan = new Scanner(System.in);		double num1=0, num2=0, answer=0, answer1=0, answer2=0, answer3=0;		String operate;		State stateObject = new State();		stateObject.statement();		End endObject = new End();		try {			Thread.sleep(500);		} catch (InterruptedException e){}		System.out.println("Please select your operator");		operate = scan.nextLine();		System.out.println("Enter first value");		num1 = scan.nextDouble();		System.out.println("Enter second value");		num2 = scan.nextDouble();		if (operate.equals ("+"))			answer = num1 + num2;		if (operate.equals("-"))			answer1 = num1 - num2;		if (operate.equals ("*"))			answer2 = num1 * num2;		if (operate.equals ("/"))			answer3 = num1 / num2;		System.out.println("Your answer is...");		if (operate.equals ("+"))			System.out.println(answer);		if (operate.equals("-"))			System.out.println(answer1);		if (operate.equals ("*"))			System.out.println(answer2);		if (operate.equals ("/"))			System.out.println(answer3);		try {			Thread.sleep(1000);		} catch (InterruptedException e){}		System.out.println("Would  you like to clear?");		System.out.println("Type yes or no.");		String s = scan.next();		if (s.contains("yes"))		main (args);		if (s.contains("no"))		endObject.finalmessage();		}			}
import java.util.Scanner;public class End {	public void finalmessage(){		@SuppressWarnings("resource")		Scanner scan2 = new Scanner(System.in);		System.out.println("Bye");		System.out.println("Type 'on' to restart");		String sentence = scan2.next();		String[] args = null;		if (sentence.contains("on"))			Calculate.main(args);		else System.out.println(" ");		}}
public class State {	int runs = 0;public void statement(){		if (runs == 0)			System.out.println("This program is a simple calculator");		if (runs < 0)			System.out.println(" ");	runs = 1;		}}
Link to comment
Share on other sites

Link to post
Share on other sites

That's because you are creating a new object every time you call main. And this is because you are still using recursion.

If you do some restructuring, like @WanderingFool said earlier the problem will disappear.

 

Something like this:

import java.io.*;public class Calculate {	BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));	State stateObject = new State();	End endObject = new End();		public void calculate() throws IOException {		double num1=0, num2=0, answer=0;		String operate;				stateObject.statement();		try {			Thread.sleep(500);		} catch (InterruptedException e){		}				System.out.println("Please select your operator");		operate = scan.readLine();		System.out.println("Enter first value");		num1 = Double.parseDouble(scan.readLine());		System.out.println("Enter second value");		num2 = Double.parseDouble(scan.readLine());				if (operate.equals ("+"))			answer = num1 + num2;		if (operate.equals("-"))			answer = num1 - num2;		if (operate.equals ("*"))			answer = num1 * num2;		if (operate.equals ("/"))			answer = num1 / num2;		System.out.println("Your answer is...");		System.out.println(answer);					try {			Thread.sleep(1000);		} catch (InterruptedException e){		}	}		public boolean wantsToContinue() throws IOException {		System.out.println("Would  you like to clear?");		System.out.println("Type yes or no.");		String s = scan.readLine();		if (s.contains("yes")) {			return true;		}		if (s.contains("no")) {			return endObject.finalmessage();		}		return false;	}		public static void main(String[] args) {		Calculate calc = new Calculate();				try {			do {				calc.calculate();			} while (calc.wantsToContinue());		} catch (IOException e) {			System.out.println("Something went wrong reading input.");		}	}	}
import java.io.*;public class End {	BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));		public boolean finalmessage() throws IOException {		System.out.println("Bye");		System.out.println("Type 'on' to restart");		String sentence = scan.readLine();		if (sentence.contains("on"))			return true;		else			return false;		}}
public class State {	int runs = 0;	public void statement(){		if (runs == 0)			System.out.println("This program is a simple calculator");		if (runs < 0)			System.out.println(" ");		runs = 1;		}}

Note that:

    1) I had to change the input method because the scanner was having trouble sometimes. The disadvantage is having to handle IOException but, since I have other things to do I handled it as late as possible (in the main);

    2) I simplified a few things that were unnecessary;

    3) This could be further simplified (you only need one class really) but I kept the three to show you that now num is not "reset"

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×