I recently made a calculator and everything is working fine except for the equal button. While it is outputting the right answer, I would like to keep using operator even after pressing equals. How can I do that?
if(e.getSource() == btnEquals) {
num2 = 0;
char operator2 = 's';
try {
display.append("=" + "\n");
for ( String line : display.getText().split("\\n")) {
char operator1 = line.charAt(line.length()-1);
num1 = Double.parseDouble(line.substring(0, line.length()-1));
if (operator2 == 's') {
num2 = num1;
operator2 = operator1;
} else if (operator2 == '+') {
num2 = num2 + num1;
operator2 = operator1;
} else if (operator2 == '-') {
num2 = num2 - num1;
operator2 = operator1;
} else if (operator2 == '*') {
num2 = num2 * num1;
operator2 = operator1;
} else if (operator2 == '/') {
num2 = num2 / num1;
operator2 = operator1;
}
}
} catch (NumberFormatException a) {
display.setText("Error: Consecutive Operators " + " (=) " + " or no input" + "\n");
return;
}
display.setText(display.getText() + num2);
}
}
When you press the button (I assume it is a Swing JButton) all the work is done in a specific thread of execution which is called event dispatch thread. As the name implies it is not the right thread for doing the heavy lifting, i.e. your current work. While you are using it it can't dispatch events for other GUI elements so you can't use any other elements.
So you need to put your business work into an extra thread and thus deal with concurrency in Swing. You can read about it here.
Wrap it with while(True) statement and will run till the exit.
Related
In this calculator program when I type in any other incorrect answer for the operator such as a number or a letter instead of +, -, *, / it shows the "wrong only operators" message but even when I put in the correct operator the same message still shows up.
How can the program not show the wrong message when I type in the correct symbol.
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
double num1, num2;
double output = 0;
char operator;
Scanner scan = new Scanner (System.in);
System.out.println("Type in first number ");
while(scan.hasNextDouble() == false)
{
System.out.println("Wrong only numbers. ");
scan.nextLine();
}
num1 = scan.nextDouble();
System.out.println("Type in the operator ");
do
{
operator = scan.next().charAt(0);
System.out.println("Wrong only operators. ");
scan.nextLine();
}
while(operator != '+' && operator != '-' && operator != '*' && operator != '/');
System.out.println("Type in second number ");
while(scan.hasNextDouble() == false)
{
System.out.println("Wrong only numbers. ");
scan.nextLine();
}
num2 = scan.nextDouble();
switch (operator)
{
case '+': output = num1 + num2; break;
case '-': output = num1 - num2; break;
case '*': output = num1 * num2; break;
case '/': output = num1 / num2; break;
}
System.out.println("" + num1 + " " + operator + " " + num2 + " = " + output);
}
}
In your case it is better to use a while loop instead of a do while.
Since you are using a do while loop : that statement is being executed at least once, not matter whether the operator is correct or not.
You can add a condition there to stop it from executing but a better way is to use while loop
import java.util.Scanner;
class Main {
public static void main(String[] args)
{
double num1, num2;
double output = 0;
char operator;
Scanner scan = new Scanner(System.in);
System.out.println("Type in first number ");
while(scan.hasNextDouble() == false)
{
System.out.println("Wrong only numbers. ");
scan.nextLine();
}
num1 = scan.nextDouble();
System.out.println("Type in the operator ");
operator = scan.next().charAt(0);
while(operator != '+' && operator != '-' && operator != '*' && operator != '/')
{
System.out.println("Wrong only operators. ");
operator = scan.next().charAt(0);
scan.nextLine();
}
System.out.println("Type in second number ");
while(scan.hasNextDouble() == false)
{
System.out.println("Wrong only numbers. ");
scan.nextLine();
}
num2 = scan.nextDouble();
switch (operator)
{
case '+': output = num1 + num2; break;
case '-': output = num1 - num2; break;
case '*': output = num1 * num2; break;
case '/': output = num1 / num2; break;
}
System.out.println("" + num1 + " " + operator + " " + num2 + " = " + output);
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I don't know why this is not working I get no compilation error here but the program always returns the else statement. Am I supposed to define operation some other way or call it someway else?
import javax.swing.JOptionPane;
public class Calculator1 {
public static void main(String []Args) {
String firstNum;
String operation;
String secondNum;
firstNum = JOptionPane.showInputDialog("Input a number.");
secondNum = JOptionPane.showInputDialog("Input another number.");
double num1 = Double.parseDouble(firstNum);
double num2 = Double.parseDouble(secondNum);
operation = JOptionPane.showInputDialog("Input an operation sign.");
if (operation == "x") {
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 );
}
if (operation == "+") {
System.out.println( num1 + num2 );
}
if (operation == "-") {
System.out.println( num1 - num2 );
}
else {
System.out.println("Please enter an appropriate operation sign.");
}
}
}
The problem is with your if statements. The else statement will always execute if operation is not equal to "-". This is because each of your if statements is a separate block of code.
if(x) {}
if(y) {}
if(z) {}
else {}
You can make this work by using else if instead of several if statements.
if(x) {}
else if(y) {}
else if(z) {}
else {}
This will work, but the correct way to do this would be to use a switch statement.
switch(operation) {
case "x": result = num1 * num2 ;
break;
case "/": result = num1 / num2;
break;
case "-": result = num1 - num2;
break,
default: System.out.println(errorMessage);
}
You should use "x".equals(operation);
First, you need use if/else structure:
if (operation == "x") {
System.out.println( num1 * num2 );
}
else if (operation == "*") {
System.out.println( num1 * num2 );
}
else if (operation == "/") {
System.out.println( num1 / num2 );
}
// Continue...
Next thing, in java, you can't compare string's content with '==' operator. You should use equals method:
if (operation.equals("x")) {
System.out.println( num1 * num2 );
}
else if (operation.equals("*")) {
System.out.println( num1 * num2 );
}
else if (operation.equals("/")) {
System.out.println( num1 / num2 );
}
// Continue...
This should works, but. Why doesn't works the '==' operator?
Strings are objects in java, you handle objects with references. So when you are doing '==', you are comparing references's address. If you want compare the content, you have to use equals method.
Another option will be use a switch:
switch(operation)
{
case "+":
System.out.println(num1 + num2);
break;
case "-":
System.out.println(num1 - num2);
break;
case "/":
System.out.println(num1 / num2);
break;
case "x":
case "*":
System.out.println( num1 * num2 );
break;
default:
System.out.println("Error!");
}
I am experiencing trouble in the creation of my reverse polish notation calculator with my validation code. I need the calculator to accept the two shift operators (<< and >>) as part of the calculations. The following snippets of code is the validation part and also the calculation.
public static boolean isInt(String userinput) {
try {
Integer.parseInt(userinput); // Try to parse. Makes sure that the values entered are actual numbers
return true; // Boolean value to show if the equation entered is valid or not
} catch (NumberFormatException e) {
System.out.println("Please enter a valid expression!");
invalidlines++;
return false;
}
}
public static boolean isValidLine(String line) {
line = line.trim();
if (line.length() <= 4) { // Trims the lines down to 4 and ensures there is no spaces being included
return false;
} else {
String[] calcarray = new String[3];
calcarray = line.split(" ");
String operators = new String("[+\\-\\*\\/\\<<\\>>\\%\\&\\|]"); // Validator using regular expressions to check the operator used
if (isInt(calcarray[0].toString()) && isInt(calcarray[1].toString()) && calcarray[2].matches(operators)) { // Checks that the operator in the string matches the ones in the regular expression
return true;
} else {
return false;
}
}
}
below is the calculator part:
String keyboardInput = new String();
Scanner kbScan = new Scanner(System.in);
int answer = 0;
while (true) {
display("Please enter an equation");
keyboardInput = kbScan.nextLine();
if (isValidLine(keyboardInput)) {
String[] equation = new String[3]; // We know that this is only going to contain 3 to be valid
equation = keyboardInput.split(" "); // split this up, as it's stored with the spaces.
int num1 = Integer.parseInt(equation[0]);
int num2 = Integer.parseInt(equation[1]);
switch (equation[2]) { // This case switch checks the third position of the
// string to decide which operator is being used. It then works out the
// answer and breaks to the next instruction
case ("+"):
answer = num1 + num2;
break;
case ("-"):
answer = num1 - num2;
break;
case ("/"):
answer = num1 / num2;
break;
case ("*"):
answer = num1 * num2;
break;
case ("<<"):
answer = num1 << num2;
break;
case (">>"):
answer = num1 >> num2;
break;
case ("%"):
answer = num1 % num2;
break;
case ("|"):
answer = num1 | num2;
break;
case ("&"):
answer = num1 & num2;
break;
}
display("Your post fix expression: " + equation[0] + " " + equation[1] + " " + equation[2]);
display("Your calculation: " + equation[0] + " " + equation[2] + " " + equation[1] + " = " + answer);
} else {
display("The equation you entered is invalid");
}
}
Whenever a valid expression is entered the following error is shown in the console:
Enter F for file calculator or K for keyboard input
k
Please enter an equation
10 2 <<
The equation you entered is invalid
Please enter an equation
And I cannot figure out which part of my validation is wrong for these expressions.
Problem is with your operators regex.
User rather something like:
("\\+|\\-|\\*|\\/|<<|>>|\\%|\\&|\\|")
Okay... I think I might have gone over my head with trying to simplify this code. I place operators such as ( *, +, /, -) in a split. Know i want to call them individually to do their perspective task in a if (operators.equals.(+)){
return num1 + num2. }
then for *, -, / perspectively
how can i do that correctly having using math in my earlier code:
String function = "[+\\-*/]+"; //this
String[] token = input.split(function);//and this
double num1 = Double.parseDouble(token[0]);
double num2 = Double.parseDouble(token[1]);
double answer;
String operator = input.toCharArray()[token[0].length()]+"";
if (operator.matches(function) && (token[0]+token[1]+operator).length()==input.length()) {
System.out.println("Operation is " + operator+ ", numbers are " + token[0] + " and " + token[1]);
} else {
System.out.println("Your entry of " + input + " is invalid");
}
You don't.
String.split only returns the parts of the String that were not matched. If you want to know the matched code, you need to use a more sophisticated regular expression, i.e. the Pattern and Matcher classes, or write your own String tokenization class yourself.
In this example Token is a class you make yourself):
public List<Token> generateTokenList(String input) {
List<Token> = new LinkedList<>();
for(char c : input.toCharArray()) {
if(Character.isDigit(c)) {
// handle digit case
} else if (c == '+') {
// handle plus
} else if (c == '-') {
// handle minus
} else {
/* you get the idea */
}
}
}
There are libraries that do this for you, such as ANTLR but this sounds like a school assignment so you probably have to do this the hard way.
Change your if body to something like
if (operator.matches(function) &&
(token[0] + token[1] + operator).length() == input.length())
{
double result = 0;
if (operator.equals("+")) {
result = num1 + num2;
} else if (operator.equals("-")) {
result = num1 - num2;
} else if (operator.equals("*")) {
result = num1 * num2;
} else if (operator.equals("/")) {
result = num1 / num2;
}
System.out.printf("%.2f %s %.2f = %.2f%n", num1, operator, num2,
result);
}
And your code works as expected.
import java.util.Scanner;
public class Improved {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number operaion number: ");
int operand1 = Integer.parseInt(input.nextLine());
char expo1 = input.next().charAt(0);
int operand2 = Integer.parseInt(input.nextLine());
System.out.println( operand1 + expo1 + operand2 + "=");
if ( expo1 == '/' && operand2 == '0' ){
System.out.println("Cannot divide by zero"); }
else
if (expo1 == '-') {
System.out.println(operand1-operand2);
} else
if (expo1 == '+') {
System.out.println(operand1+operand2);
} else
if (expo1 == '/') {
System.out.println(operand1/operand2);
} else
if (expo1 == '%') {
System.out.println(operand1%operand2);
}
else{
System.out.println(" Error.Invalid operator.");
}
}
}
//This bottom works, but I found out that this is not what is supposed to be done with this problem
/*
public class Else {
public static void main(String[] args) {
int operand1;
char exp1;
int operand2;
if (args.length != 3 ) {
System.err.println("*** Program needs 3 arguements***");
System.err.println("Usage: java Else int1 exp int2");
System.exit(1);
}
operand1 = Integer.parseInt(args[0]);
exp1 = args[1].charAt(0);
operand2 = Integer.parseInt(args[2]);
System.out.print(args[0] + args[1] + args[2] + "=");
if(exp1 == '-') {
System.out.println(operand1 - operand2);
} else
if (exp1 == '+') {
System.out.println(operand1 + operand2);
} else
if (exp1 == '/') {
System.out.println(operand1 / operand2);
} else
if (exp1 == '%') {
System.out.println(operand1 % operand2);
}
else{
System.out.println(" Error.Invalid operator.");
}
}
}
*/
What I want the program to do is ask one to enter a math operation 1/2 or 1%2 (not multiplication)
, but just like that without spaces. Still, I want to check which operation is being done which is why i put the if statements. What I don't get is how the program would know when an operation appears in a string. I'm not even sure if I set it correctly. Overall, I want a string that reads the number then the operation an then the number again. I'm sorry if this seems like doing my hw, but I have tried making this program multiple times, but can't understand how I can do this with a string. I wrote the second one to show that I have done this multiple times, so you can ignore it. Thank You very much!
read input as a String using:
String inputString = input.nextLine();
get the index of the operator:
int indexOp = inputString.indexOf("+");
if(indexOp < 0) indexOp = inputString.indexOf("-"); //cannot find +, so find -
if(indexOp < 0) indexOp = inputString.indexOf("/"); //cannot find -, so find /
if(indexOp < 0) indexOp = inputString.indexOf("%"); //cannot find /, so find %
get the first and second operand with:
int operand1 = Integer.parseInt(inputString.substring(0,indexOp));
int operand2 = Integer.parseInt(inputString.substring(indexOp+1,inputString.length());
get the operator from the indexOp we got earlier:
char operator = inputString.charAt(indexOp);
Hope it helps :)
I have no doubt there are a number of ways this might be achieved, this is simply another example...
What this tries to do, is break down the incoming text into groups of digits and non digits. It then loops through these groups making up the various elements of the calculation...
Scanner input = new Scanner(System.in);
System.out.println("Enter a number operaion number: ");
String text = input.nextLine();
System.out.println("Input = " + text);
text = text.replaceAll("\\s", "");
System.out.println("Parse = " + text);
Pattern p = Pattern.compile("\\d+|\\D+");
Matcher m = p.matcher(text);
int index = 0;
int op1 = -1;
int op2 = -2;
String exp1 = "";
while (index < 3 && m.find()) {
System.out.println(index);
String part = m.group();
switch (index) {
case 0:
op1 = Integer.parseInt(part);
break;
case 2:
op2 = Integer.parseInt(part);
break;
case 1:
exp1 = part;
break;
}
index++;
}
System.out.println(op1 + " " + exp1 + " " + op2);
What this does have, is the power to to allow you to supply a much longer calculation, for example 20+30/40-50...etc.
You would need to park each operand and exponent into some kind of List and extract them as you need them...or you could actually do the calculation directly within the while loop
Try this:
package week11;
import java.util.Scanner;
public class maths {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("enter a number ");
int x = scanner.nextInt();
System.out.println("put +, -, / or * ");
char expo1 = scanner.next().charAt(0);
System.out.println("second number please ");
int y = scanner.nextInt();
System.out.println( "Answer is" + ":");
if ( expo1 == '/' && y == '0' ){
System.out.println("cannot be divided by 0"); }
else
if (expo1 == '-') {
System.out.println(x-y);
} else
if (expo1 == '+') {
System.out.println(x+y);
} else
if (expo1 == '/') {
System.out.println(x/y);
} else
if (expo1 == '%') {
System.out.println(x%y);
}
else{
System.out.println(" Error!");
}
}
}
I would like to add another solution, which removes a lot of the parsing work.
import java.util.Scanner;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
class Scratch {
public static void main(String[] args) throws ScriptException {
System.out.println("Enter an operation:");
Scanner input = new Scanner(System.in);
String operation = input.nextLine();
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval(operation);
System.out.printf("%s = %s%n", operation, result);
}
}
sample result
Enter an operation:
2 + 3 * 4
2 + 3 * 4 = 14.0