When I add or minus or try to sum up any operation it dose not work. This is what I have and I believe it has something to do with the code that shows in the box
//////////
/////////
What am i doing wrong? The parent class has the buttons as an array.
public void actionPerformed(ActionEvent e) {
// Get the source of this action
JButton clickedButton = (JButton) e.getSource();
// Get the existing text from the calculator
// displayField.
String dispFieldText = parent.getDisplayValue();
dot = dispFieldText.contains(".");
if (!dispFieldText.equals(""))
enteredNumber = Double.parseDouble(dispFieldText);
if (clickedButton.getText().equals("+")) {
selectedAction = "+";
currentNumber = enteredNumber;
parent.setDisplayValue("");
} else if (clickedButton.getText().equals("-")) {
selectedAction = "-";
currentNumber = enteredNumber;
parent.setDisplayValue("");
} else if (clickedButton.getText().equals("*")) {
selectedAction = "*";
currentNumber = enteredNumber;
parent.setDisplayValue("");
} else if (clickedButton.getText().equals("/")) {
selectedAction = "/";
currentNumber = enteredNumber;
parent.setDisplayValue("");
////////////////////////////////////////////////////////////////////////////////
} else if ((clickedButton == parent.buttons[11]) && (selectedAction != null)) {
if (selectedAction.equals("+")) {
currentNumber += enteredNumber;
parent.setDisplayValue("" + currentNumber);
////////////////////////////////////////////////////////////////////////////////
} else if (selectedAction.equals("-")) {
currentNumber -= enteredNumber;
parent.setDisplayValue("" + currentNumber);
} else if (selectedAction.equals("*")) {
currentNumber *= enteredNumber;
parent.setDisplayValue("" + currentNumber);
} else if (selectedAction.equals("/")) {
currentNumber /= enteredNumber;
parent.setDisplayValue("" + currentNumber);
}
}
else {
if (!clickedButton.getText().equals("=")) {
if ((clickedButton.getText().equals(".")) && dot) {
}
else {
// Get the button label
String clickedButtonLabel = clickedButton.getText();
parent.setDisplayValue(dispFieldText + clickedButtonLabel);
}
}
}
}
}
Related
i have a class in a java program where i am using a toString function to retrieve data. the toString checks a private function in the same class which returns a int value, for displaying different types of return messages.~
The problem is that if i use a local variable in the string function every turns out good, but if i check in the if statements directlly the private function, this function doesnt return any value.
private int computerTryHorizontalPlay() {
int repeatedMyValueCount = 0;
int repeatedYourValueCount = 0;
int[] myPositions = new int[3];
int[] yourPositions = new int[3];
for (int a = 0; a < 3; a++) {
int repeatedMyValue = 0;
int repeatedYourValue = 0;
int emptyFields = 0;
int[] emptyPosition = new int[2];
for (int b = 0; b < 3; b++) {
if (jogoGalo[a][b] == 'X') {
repeatedMyValue++;
} else if (jogoGalo[a][b] == 'O') {
repeatedYourValue++;
}
if (jogoGalo[a][b] == '-') {
emptyPosition[0] = a;
emptyPosition[1] = b;
emptyFields++;
}
}
if (repeatedMyValue == 3 || repeatedYourValue == 3) {
return 3;
} else {
if (emptyFields == 1) {
if (repeatedMyValue == 2) {
repeatedMyValueCount++;
myPositions[repeatedMyValueCount - 1] = emptyPosition[0];
myPositions[repeatedMyValueCount] = emptyPosition[1];
} else if (repeatedYourValue == 2) {
repeatedYourValueCount++;
yourPositions[repeatedYourValueCount - 1] = emptyPosition[0];
yourPositions[repeatedYourValueCount] = emptyPosition[1];
}
}
}
}
if (repeatedMyValueCount > 0) {
jogoGalo[myPositions[0]][myPositions[1]] = 'X';
return 2;
} else if (repeatedYourValueCount > 0) {
jogoGalo[yourPositions[0]][yourPositions[1]] = 'X';
return 1;
}
return 0;
}
This doesn´t work!
public String toString() {
if(computerTryHorizontalPlay() == 3) {
return "The game has already ended!";
}
else if(computerTryHorizontalPlay() == 2) {
return "Computer won!";
}
else if(computerTryHorizontalPlay() == 1) {
return "Computer defendeu!";
}
return null;
}
This works!
public String toString() {
int horizontalFunctionValue = computerTryHorizontalPlay();
if(horizontalFunctionValue == 3) {
return "The game has already ended!";
}
else if(horizontalFunctionValue == 2) {
return "Computer won!";
}
else if(horizontalFunctionValue == 1) {
return "Computer defendeu!";
}
return null;
}
}
toString() must be a read-only method, i.e. it is not allowed to have side-effects like changing the state of the object. Since computerTryHorizontalPlay() is a state-changing method, you are not allowed to call it from toString().
Since the only state-change happens in the last if statement, you can change the code to not execute the play when called from toString(), like this:
private int computerTryHorizontalPlay() {
return computerTryHorizontalPlay(true);
}
private int computerTryHorizontalPlay(boolean doMove) {
// lots of code here
if (repeatedMyValueCount > 0) {
if (doMove)
jogoGalo[myPositions[0]][myPositions[1]] = 'X';
return 2;
} else if (repeatedYourValueCount > 0) {
if (doMove)
jogoGalo[yourPositions[0]][yourPositions[1]] = 'X';
return 1;
}
return 0;
}
public String toString() {
if(computerTryHorizontalPlay(false) == 3) {
return "The game has already ended!";
}
else if(computerTryHorizontalPlay(false) == 2) {
return "Computer won!";
}
else if(computerTryHorizontalPlay(false) == 1) {
return "Computer defeated!";
}
return null;
}
This question already has answers here:
Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String
(3 answers)
Closed 3 years ago.
I am a bit new to java and was hoping if anyone could help me. I'm writing this code on virtual machine Ubuntu using the text editor. The RAM errors is right here if you would like to reference the file. http://users.cis.fiu.edu/~crahn/CGS3767/RAMerrors. The error is located in the public static readingLine in the System.out.printf. If anyone could help me idenify the error, I would greatly appreciate it. Thank you!
import java.io.*;
import java.util.*;
public class MemoryCalculator
{
private static Scanner convertingFiles;
public static String convertFile = "RAMerrors.txt";
public static void readFile(String nameOfFile) throws IOException
{
convertingFiles = new Scanner(new File(nameOfFile));
}
public static void readingLine(String nameOfFile) throws IOException
{
System.out.println();
int recordingNum = 0;
while(convertingFiles.hasNext())
{
recordingNum = recordingNum +1;
String recordingLine = convertingFiles.nextLine();
System.out.printf("( %d) %g ) \n", recordingNum, recordingLine );
String conv = fromHexToBi(recordingLine);
long decimal = fromBiToDec(conv);
System.out.println(errorRamRangeWeb(decimal));
}
}
public static String fromHexToBi(String input)
{
int fromHexToBi = 0;
String record = "";
char var;
for(int x = 0; x < input.length(); x++)
{
var = input.charAt(x);
if(var == '0')
{
record += "0000";
}
else if (var == '1')
{
record += "0001";
}
else if (var == '2')
{
record += "0010";
}
else if (var == '3')
{
record += "0011";
}
else if (var == '4')
{
record += "0100";
}
else if (var == '5')
{
record += "0101";
}
else if (var == '6')
{
record += "0110";
}
else if (var == '7')
{
record += "0111";
}
else if (var == '8')
{
record += "1000";
}
else if (var == '9')
{
record += "1001";
}
else if (var == 'A')
{
record += "1010";
}
else if (var == 'B')
{
record += "1011";
}
else if (var == 'C')
{
record += "1100";
}
else if (var == 'D')
{
record += "1101";
}
else if (var == 'E')
{
record += "1110";
}
else if (var == 'F')
{
record += "1111";
}
else
{
System.out.print("Sorry, the error is .out of range");
}
}
System.out.println(record);
return record;
}
public static long fromBiToDec(String bi)
{
long decimal = 0;
for(int y = 0; y < bi.length(); y++)
{
if(bi.charAt(y) == '1')
{
decimal = (long) (decimal + Math.pow(2, bi.length() - 1 - y));
}
}
System.out.println(decimal);
return (long) decimal;
}
public static String errorRamRangeWeb(long decimal)
{
String chipRangeFall = "";
long errorRamRange0 = 0;
long errorRamRange1 = 8589934584L;
long errorRamRange2 = 8589934585L;
long errorRamRange3 = 1717986184L;
long errorRamRange4 = 17179869185L;
long errorRamRange5 = 25769803768L;
long errorRamRange6 = 25769803769L;
long errorRamRange7 = 34359738368L;
long result = decimal;
if((result >= errorRamRange0) && (result <= errorRamRange1))
{
chipRangeFall = "1";
}
else if ((result >= errorRamRange2) && (result <= errorRamRange5))
{
chipRangeFall = "2";
}
else if ((result >= errorRamRange4) && (result <= errorRamRange3))
{
chipRangeFall = "3";
}
else if ((result >= errorRamRange6) && (result <= errorRamRange7))
{
chipRangeFall = "4";
}
else
{
System.out.println("ram chip does not exist");
}
return chipRangeFall;
}
public static void main(String[] args) throws IOException
{
readFile(convertFile);
readingLine(convertFile);
}
}
You want a %s conversion for your String argument recordingLine, not %g
recordingLine is expected to be float but found to be string.
I have a JTextField.I want after each character the user types,a method call and change the order of character in same JTextField,but in my code displayArrestNo2() method call and print in consol right answer but dont update content of JTextField.How can do it?
public static void main(String args[]) {
final JTextField textField = new JTextField();
textField.setSize(100, 100);
textField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
}
public void removeUpdate(DocumentEvent e) {
}
public void insertUpdate(DocumentEvent e) {
try{
Stringx=displayArrestNo2(e.getDocument().getText(0,e.getDocument().getLength()));
System.out.println(x);
}catch(Exception ex){
ex.printStackTrace();
}
}
public void warn() {
}
public String displayArrestNo2(String aValue){
System.out.println("oroginal value: " + aValue);
aValue = " "+aValue+" ";
System.out.println("space added value: "+aValue);
final String validStr = " ابپتثجچحخدرزژسشصضطظعغفقکگلمنوهیي";
int lPos, fPos, i, j, k;
boolean flgEnterIntSection, lastWasChar;
String result = "";
flgEnterIntSection= false;
lastWasChar = false;
lPos = 0;
i = aValue.length()-1;
while( i >= 0) {
char[] aValueArr = aValue.toCharArray();
/* char[] tmpArr = aValue.toCharArray();
char[] aValueArr = new char[tmpArr.length];
for(int x=0; x<tmpArr.length; x++)
aValueArr[x]= tmpArr[tmpArr.length-x-1]; */
if (aValueArr[i] == 'ß')
aValueArr[i] = '˜';
if (convert(aValueArr[i]) == -1)
{
if(validStr.indexOf(aValueArr[i]) > 0)
{
j = 0;
while ( ( (i - j) > 0) && (validStr.indexOf(aValueArr[i-j]) > 0 ))
j = j + 1;
if (j >1)//j>1
{
k = j;
while (j > 0)
{
result = result + aValueArr[i - j+1];//i-j+1
j--;
}
i = i - k+1;//i-k+1
}
else
result = result + aValueArr[i];
}
else
result = result + aValueArr[i];
i--;
flgEnterIntSection = false;
}
else
{
fPos = i;
j = i;
while ((j >= 0) && ((!flgEnterIntSection) || (convert(aValueArr[j]))!=-1))// (StrToIntDef(AValue[j], -1) <> -1)
{
flgEnterIntSection = true;
while ((j >= 0) && (convert(aValueArr[j]))!=-1) // StrToIntDef(AValue[j], -1) <> -1)
j--;
if ((j > 0) && ((aValueArr[j] == '.') || (aValueArr[j] == '/')) )
if (((j-1) >= 0) && (convert(aValueArr[j-1]))!=-1) //StrToIntDef(AValue[j - 1], -1) <> -1)
j--;
}
lPos = j + 1;
for (j = lPos; j <= fPos; j++)
{
result = result + aValueArr[j];
}
i = lPos-1;
}
}
// return result;
// System.out.println("before reverse "+result);
return reverseOrder(result);
}
String reverseOrder(String input){
String [] inArr = input.split(" ");
String reversed = "";
for(int i = inArr.length-1; i>=0; i--){
reversed += inArr[i] + " ";
}
return reversed;
}
public int convert(char ch) {
try {
int m = Integer.parseInt(String.valueOf(ch));
return m;
} catch (Exception e) {
return -1;
}
}
TestJTextField x=new TestJTextField();
x.add(textField);
x.setVisible(true);
}
in insertUpdate() method ,displayArrestNo2() is called per character but dont change content of JTextField.
I'm searching for ways on how to compute mathematical expressions that can compute inputs with string such as sin(90) and 10E8, until I saw these codes which I can't fully understand how these works. I want to make these as a basis because I want to improve my MDAS calculator.
I am having difficulty on understanding these codes. I'm not familiar with StringBuffer, StringTokenizer, Math.ceil, ans += mul(); , ( b.toString(), "\t" ); , but I have idea on how the trigonometric function & MDAS operation works.
Update: I've understand what is StringTokenizer but what is its relation with StringBuffer?
import java.util.*;
public class Expression {
String s, x;
double term() {
double ans = 0;
StringBuffer temp = new StringBuffer();
while (s.length() > 0 && Character.isDigit(s.charAt(0))) {
temp.append(Integer.parseInt("" + s.charAt(0)));
s = s.substring(1);
}
if (s.length() > 0 && s.charAt(0) == '.') {
temp.append('.');
s = s.substring(1);
while (s.length() > 0 && Character.isDigit(s.charAt(0))) {
temp.append(Integer.parseInt("" + s.charAt(0)));
s = s.substring(1);
}
}
if (s.length() > 0 && (s.charAt(0) == 'e' || s.charAt(0) == 'E')) {
temp.append('e');
s = s.substring(1);
temp.append(s.charAt(0));
s = s.substring(1);
while (s.length() > 0 && Character.isDigit(s.charAt(0))) {
temp.append(Integer.parseInt("" + s.charAt(0)));
s = s.substring(1);
}
}
ans = Double.valueOf(temp.toString()).doubleValue();
return ans;
}
double paren() {
double ans;
if (s.charAt(0) == '(') {
s = s.substring(1);
ans = add();
s = s.substring(1);
} else {
ans = term();
}
return ans;
}
double exp() {
boolean neg = false;
if (s.charAt(0) == '-') {
neg = true;
s = s.substring(1);
}
double ans = paren();
while (s.length() > 0) {
if (s.charAt(0) == '^') {
s = s.substring(1);
boolean expNeg = false;
if (s.charAt(0) == '-') {
expNeg = true;
s = s.substring(1);
}
double e = paren();
if (ans < 0) {
double x = 1;
if (Math.ceil(e) == e) {
if (expNeg)
e *= -1;
if (e == 0)
ans = 1;
else if (e > 0)
for (int i = 0; i < e; i++)
x *= ans;
else
for (int i = 0; i < -e; i++)
x /= ans;
ans = x;
} else {
ans = Math.log(-1);
}
} else if (expNeg)
ans = Math.exp(-e * Math.log(ans));
else
ans = Math.exp(e * Math.log(ans));
} else
break;
}
if (neg)
ans *= -1;
return ans;
}
double trig() {
double ans = 0;
boolean found = false;
if (s.indexOf("sin") == 0) {
s = s.substring(3);
ans = Math.sin((trig() * Math.PI) / 180);
found = true;
} else if (s.indexOf("cos") == 0) {
s = s.substring(3);
ans = Math.cos((trig() * Math.PI) / 180);
found = true;
} else if (s.indexOf("tan") == 0) {
s = s.substring(3);
ans = Math.tan((trig() * Math.PI) / 180);
found = true;
}
if (!found) {
ans = exp();
}
return ans;
}
double mul() {
double ans = trig();
if (s.length() > 0) {
while (s.length() > 0) {
if (s.charAt(0) == '*') {
s = s.substring(1);
ans *= trig();
} else if (s.charAt(0) == '/') {
s = s.substring(1);
ans /= trig();
} else
break;
}
}
return ans;
}
double add() {
double ans = mul();
while (s.length() > 0) {
if (s.charAt(0) == '+') {
s = s.substring(1);
ans += mul();
} else if (s.charAt(0) == '-') {
s = s.substring(1);
ans -= mul();
} else {
break;
}
}
return ans;
}
public double evaluate() {
s = x.intern();
double last = add();
return last;
}
public Expression(String s) {
StringBuffer b = new StringBuffer();
StringTokenizer t = new StringTokenizer(s, " ");
while (t.hasMoreElements())
b.append(t.nextToken());
t = new StringTokenizer(b.toString(), "\t");
b = new StringBuffer();
while (t.hasMoreElements())
b.append(t.nextToken());
x = b.toString();
}
public String toString() {
return x.intern();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter expression: ");
Expression e = new Expression(sc.nextLine());
System.out.println("\n" + e + " = " + e.evaluate() + "\n");
}
}
This program is generally reading in a string representation of a mathematical expression, and interpreting and executing that expression. As for the Java elements you're curious about:
StringBuffer is a more efficient interface to manipulating String objects.
StringTokenizer(String, String) is a class to break a string into tokens. In this constructor, the first argument is a string to break into tokens, the second argument is the delimiter used to create those tokens.
Math.ceil() returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer.
StringBuffer.toString() writes out a String representing the data in the buffer
\t is a tab
+= and -= are the {add/ subtract} assignment operators, which {add / subtract} right operand to the left operand and assign the result to left operand. E.g.
int x = 0;
x += 2; // x is now 2
See javadoc for StringBuffer at http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html
See javadoc for StringTokenizerat http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html
I will try to comment all but the obvious lines
import java.util.*;
public class Expression {
String s, x;
double term() {
double ans = 0;
StringBuffer temp = new StringBuffer(); //Efficient than simple String
while (s.length() > 0 && Character.isDigit(s.charAt(0))) { //Check if the first character is a digit
temp.append(Integer.parseInt("" + s.charAt(0))); //If true, add to temp String
s = s.substring(1);
}
if (s.length() > 0 && s.charAt(0) == '.') {
temp.append('.');
s = s.substring(1);
while (s.length() > 0 && Character.isDigit(s.charAt(0))) {
temp.append(Integer.parseInt("" + s.charAt(0)));
s = s.substring(1);
}
}
if (s.length() > 0 && (s.charAt(0) == 'e' || s.charAt(0) == 'E')) {
temp.append('e');
s = s.substring(1);
temp.append(s.charAt(0));
s = s.substring(1);
while (s.length() > 0 && Character.isDigit(s.charAt(0))) {
temp.append(Integer.parseInt("" + s.charAt(0)));
s = s.substring(1);
}
}
ans = Double.valueOf(temp.toString()).doubleValue();
return ans;
}
double paren() {
double ans;
if (s.charAt(0) == '(') {
s = s.substring(1);
ans = add();
s = s.substring(1);
} else {
ans = term();
}
return ans;
}
double exp() {
boolean neg = false;
if (s.charAt(0) == '-') {
neg = true;
s = s.substring(1);
}
double ans = paren();
while (s.length() > 0) {
if (s.charAt(0) == '^') {
s = s.substring(1);
boolean expNeg = false;
if (s.charAt(0) == '-') {
expNeg = true;
s = s.substring(1);
}
double e = paren();
if (ans < 0) {
double x = 1;
if (Math.ceil(e) == e) { //Check Math.ceil documentation at http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#ceil(double)
if (expNeg)
e *= -1;
if (e == 0)
ans = 1;
else if (e > 0)
for (int i = 0; i < e; i++)
x *= ans;
else
for (int i = 0; i < -e; i++)
x /= ans;
ans = x;
} else {
ans = Math.log(-1); //http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#log(double)
}
} else if (expNeg)
ans = Math.exp(-e * Math.log(ans));
else
ans = Math.exp(e * Math.log(ans)); //http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#exp(double)
} else
break;
}
if (neg)
ans *= -1;
return ans;
}
double trig() {
double ans = 0;
boolean found = false;
if (s.indexOf("sin") == 0) {
s = s.substring(3);
ans = Math.sin((trig() * Math.PI) / 180);
found = true;
} else if (s.indexOf("cos") == 0) {
s = s.substring(3);
ans = Math.cos((trig() * Math.PI) / 180);
found = true;
} else if (s.indexOf("tan") == 0) {
s = s.substring(3);
ans = Math.tan((trig() * Math.PI) / 180);
found = true;
}
if (!found) {
ans = exp();
}
return ans;
}
double mul() {
double ans = trig();
if (s.length() > 0) {
while (s.length() > 0) {
if (s.charAt(0) == '*') {
s = s.substring(1);
ans *= trig();
} else if (s.charAt(0) == '/') {
s = s.substring(1);
ans /= trig();
} else
break;
}
}
return ans;
}
double add() {
double ans = mul();
while (s.length() > 0) {
if (s.charAt(0) == '+') {
s = s.substring(1);
ans += mul();
} else if (s.charAt(0) == '-') {
s = s.substring(1);
ans -= mul();
} else {
break;
}
}
return ans;
}
public double evaluate() {
s = x.intern();
double last = add();
return last;
}
public Expression(String s) {
StringBuffer b = new StringBuffer();
StringTokenizer t = new StringTokenizer(s, " "); //Creates a iterable t object so you can iterate over each "word" separate by space
while (t.hasMoreElements())
b.append(t.nextToken());
t = new StringTokenizer(b.toString(), "\t");
b = new StringBuffer();
while (t.hasMoreElements())
b.append(t.nextToken());
x = b.toString();
}
public String toString() {
return x.intern();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter expression: ");
Expression e = new Expression(sc.nextLine());
System.out.println("\n" + e + " = " + e.evaluate() + "\n");
}
}
I've made a simple calculator. What happens is I convert the user input to infixtopostfix and then evaluate it. Everything works fine except when the user does something like 3^2, the program doesn't convert it to post fix correctly. It should be converting it to 32^ but it's converting it to ^32. Could someone please explain to me what is wrong with my convert method that is causing this issue.
Convert method:
static String convert(String infix)
{
ArrayStack<Character> as = new ArrayStack<Character>(infix.length());
String post_expression = "";
int index = 0;
while(index < infix.length()) {
char current = infix.charAt(index);
if(current == ' ') {
index++;
continue;
}
else if(current == '(') {
as.push(current);
}
else if(current == ')') {
while(as.top() != '(') {
post_expression += as.pop();
}
as.pop();
}
else if(current == '=')
{
index++;
continue;
}
else if(current == '^')
{
post_expression += as.pop();
}
else {
while(!as.isEmpty() && as.top() > current) {
post_expression += as.pop();
}
as.push(current);
}
index++;
}
while(!as.isEmpty()) {
post_expression += as.pop();
}
return post_expression;
}
Complete Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.*;
import java.io.*;
class Calculator2 extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn_add = new JButton("+");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn_sub = new JButton("-");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
JButton btn_mult = new JButton("*");
JButton btn0 = new JButton("0");
JButton btn_dot = new JButton(".");
JButton btn_del = new JButton("DEL");
JButton btn_div = new JButton("/");
JButton btn_lpr = new JButton("(");
JButton btn_rpr = new JButton(")");
JButton btn_pow = new JButton("^");
JButton btn_equ = new JButton("=");
JTextArea txt = new JTextArea();
String str_number = "";
public Calculator2() {
JFrame frame = new JFrame("Simple Java Caculator");
frame.setSize(320,420);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
frame.setLayout(new GridLayout(2,1));
JPanel HeadPanel = new JPanel();
JPanel NumberPanel = new JPanel();
JPanel LabelPanel = new JPanel();
LabelPanel.setBackground(Color.LIGHT_GRAY);
HeadPanel.setBackground(Color.LIGHT_GRAY);
NumberPanel.setLayout(new GridLayout(5,4));
//LabelPanel.setLayout(new BorderLayout());
LabelPanel.setLayout(new GridLayout(1,1));
NumberPanel.add(btn1);
btn1.addActionListener(this);
NumberPanel.add(btn2);
btn2.addActionListener(this);
NumberPanel.add(btn3);
btn3.addActionListener(this);
NumberPanel.add(btn_add);
btn_add.addActionListener(this);
NumberPanel.add(btn4);
btn4.addActionListener(this);
NumberPanel.add(btn5);
btn5.addActionListener(this);
NumberPanel.add(btn6);
btn6.addActionListener(this);
NumberPanel.add(btn_sub);
btn_sub.addActionListener(this);
NumberPanel.add(btn7);
btn7.addActionListener(this);
NumberPanel.add(btn8);
btn8.addActionListener(this);
NumberPanel.add(btn9);
btn9.addActionListener(this);
NumberPanel.add(btn_mult);
btn_mult.addActionListener(this);
NumberPanel.add(btn0);
btn0.addActionListener(this);
NumberPanel.add(btn_dot);
btn_dot.addActionListener(this);
NumberPanel.add(btn_del);
btn_del.addActionListener(this);
NumberPanel.add(btn_div);
btn_div.addActionListener(this);
LabelPanel.add(txt);
//LabelPanel.add(btn_equ);
NumberPanel.add(btn_lpr);
btn_lpr.addActionListener(this);
NumberPanel.add(btn_rpr);
btn_rpr.addActionListener(this);
NumberPanel.add(btn_pow);
btn_pow.addActionListener(this);
NumberPanel.add(btn_equ);
btn_equ.addActionListener(this);
txt.setEditable(false);
//btn_del.setEnabled(false);
HeadPanel.add(new JLabel("A Java Calculator"));
frame.add(LabelPanel);
frame.add(NumberPanel);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btn1) {
str_number+="1";
txt.setText(str_number); }
else if(e.getSource()==btn2) {
str_number+="2";
txt.setText(str_number); }
else if(e.getSource()==btn3) {
str_number+="3";
txt.setText(str_number); }
else if(e.getSource()==btn4) {
str_number+="4";
txt.setText(str_number); }
else if(e.getSource()==btn5) {
str_number+="5";
txt.setText(str_number); }
else if(e.getSource()==btn6) {
str_number+="6";
txt.setText(str_number); }
else if(e.getSource()==btn7) {
str_number+="7";
txt.setText(str_number); }
else if(e.getSource()==btn8) {
str_number+="8";
txt.setText(str_number); }
else if(e.getSource()==btn9) {
str_number+="9";
txt.setText(str_number); }
else if(e.getSource()==btn0) {
str_number+="0";
txt.setText(str_number); }
else if(e.getSource()==btn_lpr) {
str_number+="(";
txt.setText(str_number); }
else if(e.getSource()==btn_rpr) {
str_number+=")";
txt.setText(str_number); }
else if(e.getSource()==btn_pow) {
str_number+="^";
txt.setText(str_number); }
else if(e.getSource()==btn_add) {
str_number+="+";
txt.setText(str_number);}
else if(e.getSource()==btn_sub) {
str_number+="-";
txt.setText(str_number);}
else if(e.getSource()==btn_mult) {
str_number+="*";
txt.setText(str_number);}
else if(e.getSource()==btn_div) {
str_number+="/";
txt.setText(str_number);}
else if(e.getSource()==btn_equ) {
System.out.println("you clicked equal sign!");
str_number+="=";
txt.setText(str_number);
String expression = convert(str_number);
double eval = evaluate(expression);
str_number+=eval;
txt.setText(str_number);
}
else if(e.getSource()==btn_dot) {
System.out.println("you clicked dot button!");
str_number+=".";
txt.setText(str_number);
}
else if(e.getSource()==btn_del) {
System.out.println("you clicked DEL button!");
if(str_number.length() > 0)
{
str_number = str_number.substring(0, str_number.length() - 1);
}
txt.setText(str_number);
}
}
static String convert(String infix)
{
ArrayStack<Character> as = new ArrayStack<Character>(infix.length());
String post_expression = "";
int index = 0;
while(index < infix.length()) {
char current = infix.charAt(index);
if(current == ' ') {
index++;
continue;
}
else if(current == '(') {
as.push(current);
}
else if(current == ')') {
while(as.top() != '(') {
post_expression += as.pop();
}
as.pop();
}
else if(current == '=')
{
index++;
continue;
}
else if(current == '^')
{
post_expression += as.pop();
}
else {
while(!as.isEmpty() && as.top() > current) {
post_expression += as.pop();
}
as.push(current);
}
index++;
}
while(!as.isEmpty()) {
post_expression += as.pop();
}
return post_expression;
}
static double evaluate(String postfix) {
ArrayStack as = new ArrayStack(postfix.length());
char nextChar = 'm';
int index = 0;
double temp = 0.00;
while(index < postfix.length()) {
char current = postfix.charAt(index);
if(current == ' ') {
index++;
continue;
}
if(!(current == '+' || current == '-' || current == '*' || current == '/'))
{
as.push(current);
temp = (double) (current - '0');
}
else {
char a = (char) as.pop();
char b = (char) as.pop();
double c = (double) (a - '0');
double d = (double) (b - '0');
switch(current) {
case '+' :
temp = d + c;
break;
case '-' :
temp = d - c;
break;
case '*' :
temp = d * c;
break;
case '/' :
temp = d / c;
break;
case '^' :
temp = Math.pow(d, c);
break;
}
as.push(nextChar);
nextChar++;
}
index++;
}
if(as.size() == 1) {
as.pop();
}
else {
System.out.println("There is an error");
}
return temp;
}
public static void main(String[] args) {
new Calculator2();
}
}
ArrayStack code
public class ArrayStack<E> implements Stack<E> {
protected int capacity;
public static final int CAPACITY = 1000;
protected E S[];
protected int top = -1;
public ArrayStack() {
this(CAPACITY);
}
public ArrayStack(int cap) {
capacity = cap;
S = (E[]) new Object[capacity];
}
#Override
public int size() {
return top+1;
}
#Override
public boolean isEmpty() {
return (top < 0);
}
#Override
public E top() throws EmptyStackException {
if(isEmpty())
throw new EmptyStackException("Stack is empty!");
return S[top];
}
#Override
public void push(E element) {
if(size() == capacity)
throw new FullStackException("Stack is full");
S[++top] = element;
}
#Override
public E pop() throws EmptyStackException {
E element;
if(isEmpty())
throw new EmptyStackException("Stack is empty");
element = S[top];
S[top--] = null;
return element;
}
#Override
public String toString() {
String s;
s = "[";
if(size() > 0) s += S[0];
if(size() > 1)
for(int i = 1; i <= size()-1; i++) {
s += ", " + S[i];
}
return s + "]";
}
}