our assignment is we are going to create a calculator(console based) in JAVA
but my problem is
how could I make equal sign as a terminator..

for example i'll add 5+10.

if i press equal.. the answer will come out instead of pressing enter key..

Edited 5 Years Ago by HesterSuma2007: n/a

Try using ascii value for equal operator...

I think u want to terminate method execution when press = symbol....

You'd need something like cbreak mode, which I think you can't get in the console under java. Same reason you can't clear the screen, except by sending a large number of carriage returns.

here is a sample code:

import java.io.*;
pulic class calc{
public static void main(String[] args)throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));


String num=Iin.readLine();  // assuming I entered 5+5
                            // then after that i press equal
                            // then the answer will come out.


}
}
 // how could this be possible without pressing enter key =(

// how could I insert the character equal(=) ascii code 61??

Edited 3 Years Ago by Nick Evan: Fixed formatting

The question is really, how do you read characters as they are typed, instead of after the enter key is pressed. In System.in, I don't know of a way.
You could maybe fake it, to some degree, by instantiating and hiding a Swing component capable of taking a keyListener, and sending the keys typed to the standard out, unless they're '='. But that's a pretty rubegoldbergian solution - not one I would suggest you actually use.

If I'm wrong, and there's a way to get console input on a character-by-character basis, I hope someone will chime in with it.

Hester, with this being such a basic starter example, I don't suggest jon's keyListener hide & seek method. Perhaps you haven't fully read the assignment? Are you certain you are not allowed to hit enter or are you just assuming that you can't? Don't think of enter as a key stroke, but rather think of it as the button that commits your other keystrokes into the console.

What I mean is that it is probably safe to assume this type of input:

3 [enter]
+ [enter]
5 [enter]
= [enter]
<output displayed>

or, they have to enter something like

5+7 - 8 =

, store this input in an array of characters and checking for the first occurance of =. when they 've found this, they can go puzzeling (adding, subtracting, ... ) all before this point. even an indexOf("=") could do this.

Edited 5 Years Ago by stultuske: n/a

Stult--thats a bad idea, I think. Calculator logic has historically been intrinsic on the very little memory available to them. With your method, I could do 5 + 7 + 7 ... and continue entering an operand and operator until I run out of memory without actually outputting anything to the console. Logically, there should be an output in between operators (+, -, *, /, =).

The logic probably needs to model something like this:

5 [enter]
+ [enter]
7 [enter]
12 <auto output>
- [enter]
8 [enter]
4 <auto output>
= [enter]
0 <auto output>
= [enter]
-4 <auto output>

With this logic, only the left operand, right operand, and the operator are stored in memory and only when "=" is invoked. Any other operator, you only need to store the left operand, the operator, and get the data from input. Also, "=" doesn't quite match a traditional calculator with this logic, but there is no other way without invoking a keylistener (which I'm not even sure is possible on the console, but certainly outside the scope of this student's assignment). Basically, the "=" only acts to repeat the previous operator action.

Thank sir's

but the input must be in a single expression.

like if I input 5+6+10-8*3/2= only once before pressing ENTER

not
5 [enter]
+ [enter]
5 [enter] ....

how could I do that.. if I used
int num = Integer.parseInt(in.readLine()); //as input and I inputted 5+6+10-8*3/2=
there will be an error occured.
but if
String num = in.readLine(); // as input and I inputted 5+6+10-8*3/2=
there will no error.. but again my problem is how could I come up with the output of 5+6+10-8*3/2= if it is in a String form, how could I possibly do it one at a time.. if I use charAt to check the string one by one... hmmm

ahh, this is more of a in/post-fix problem.

You need to read the whole line in as a String (e.g. Scanner class). Then, parse the string into pieces. There are several ways you could solve this. One way would be to split the string one operator at a time.

String line = "4+5*2=";
String[] addition = line.split("+"); // ["4", "5*2="];

Lots of overhead doing it this way. Another way to solve this is:

String line = "4+5*2=";
char[] tokens = line.toCharArray(); // ;

Then its just a matter of converting the tokens (from infix notation) into post-fix notation and solving. Hopefully that makes sense; I assume you've had a lecture on pre/in/post-fix notation at some point, if you're studying Java.

Hint: you want this post-fix notation: "52*4+"

If you're not familiar with pre/in/post-fix, you could always brute-force solve it. That is, check for * and /, solve; then check for + and -, solve. This is very inefficient since you have to scan the entire string multiple times, instead of just twice when solving with in-fix and post-fix.

thank you sir... here is the code in converting an infix to postfix

but my problem is how could I come up with the final answer.. assuming i the input "9+2*3/2-1" // = 11;

postfix output is = "923*2/+1-" // this is = to 11;

and now base on the postfix output which is in String form.. how could I come up with an answer of 11?

import java.util.Scanner;
import java.util.Stack;
public class Calculator {

public static void main(String[] args){
System.out.println("Enter an expression ");
Scanner scanner = new Scanner(System.in);
String expression = scanner.nextLine();
new Calculator(expression);
}


private Stack<String> stack;
private String infixExp;
private String postfixExp = "";

public Calculator(String exp){

String str = "";
String postfix="";
infixExp = exp;

stack = new Stack<String>();

for (int i=0;i<infixExp.length();i++){
str = infixExp.substring(i,i+1);
if(str.matches("[a-zA-Z]|\\d"))
postfixExp += str;
else if (isOperator(str)){
if (stack.isEmpty()){
stack.push(str);
}
else{
String stackTop = stack.peek();
while (getPrecedence(stackTop,str).equals(stackTop)&& !(stack.isEmpty())){
postfixExp += stack.pop();
if (!(stack.isEmpty()))
stackTop = stack.peek();
}
stack.push(str);
}
}
}

while(!(stack.isEmpty()))
postfixExp += stack.pop();
postfix=postfix+postfixExp;
System.out.println("The postfix form is: " + postfix);

}

private boolean isOperator(String ch){
String operators = "*/%+-";
if (operators.indexOf(ch) != -1)
return true;
else
return false;
}

private String getPrecedence(String op1, String op2){

String multiplicativeOps = "*/%";
String additiveOps = "+-";
if ((multiplicativeOps.indexOf(op1) != -1) && (additiveOps.indexOf(op2) != -1))
return op1;
else if ((multiplicativeOps.indexOf(op2) != -1) && (additiveOps.indexOf(op1) != -1))
return op2;
else if((multiplicativeOps.indexOf(op1) != -1) && (multiplicativeOps.indexOf(op2) != -1))
return op1;
else
return op1;
}
}

Great job converting to post-fix notation!

Now its just a matter of solving, so your logic might look like this:

Stack:
Queue: 9 2 3 * 2 / + 1 -

Stack: 9
Queue: 2 3 * 2 / + 1 -

Stack: 9 2
Queue: 3 * 2 / + 1 -

Stack: 9 2 3
Queue: * 2 / + 1 -

Stack: 9 2 3 *
Queue: 2 / + 1 -

Stack: 9 6
Queue: 2 / + 1 -

Stack: 9 6 2
Queue: / + 1 -

Stack: 9 6 2 /
Queue: + 1 -

Stack: 9 3
Queue: + 1 -

Stack: 9 3 +
Queue: 1 -

Stack: 12
Queue: 1 -

Stack: 12 1
Queue: -

Stack: 12 1 -
Queue:

Stack: 11
Queue:

Basically, you want to keep pushing onto the stack until you reach an operator. If you do, pop the last 2 operands, perform the operation, and push the result onto the stack. The great thing about going from in-fix to post-fix notation is 1) no parenthesis to deal with, and 2) very simple algorithm for solving long chains of arithmetic with very little memory required.

Post back with your final code in action!

Comments
Thanks ... this helps a lot

Hmm... But go back to your original question, the last key to terminate or let the program to compute is still 'Enter' key not '=', isn't it? You are using 'nextLine()' and that's the reason why you cannot make it work. You need to read in each character and keep checking whether it is a '=' or 'enter'; otherwise, you would have to keep looping and wait for the correct char. You would also control the input at the same time (sanitize whatever coming in). The portion of reading in one char at a time could be...

char ch;
try {
  ch = (char)System.in.read();
}
catch (Exception e) { }

Edited 5 Years Ago by Taywin: n/a

Taywin, please read the entire thread before posting.

The OP is looking to read in an entire line, such as "9+2*3/2-1=", with 1 enter stroke.

Not, 9 [enter] + [enter] 2 [enter] ... etc

By reading the entire line in what is presumed to be in-fix notation, it can easily be parsed into post-fix notation and solved with O(n) efficiency.

public class Thanks{
public static void main(String[] args){

System.out.println("hi ztini... thank you very much... I've already did it... thank you for your help,for sharing ideas and the logic.");

}
}

This article has been dead for over six months. Start a new discussion instead.