AWT Choice in a calculator - java

I basically don't know how to forward the value I get from a Choice and use it in a equation later on.
I'm building a calculator and I need to have a Choice control with operations and a button that calculates with the operation selected in the Choice.
b1 = Calculate button
This is the equation I use
Double n1 = Double.parseDouble(t1.getText());
Double n2 = Double.parseDouble(t2.getText());
if (e.getSource() == b1) {
t3.setText(String.valueOf(n1 [here should be the operator selected from the Choice] n2)); }
The idea is when clicked on the button Calculate n1 and n2 should perform operation selected in Choice control.
[enter image description here](https://i.stack.imgur.com/9Dqwa.png)

Check the API documentation about Choice. That class offers the methods
getSelectedItem() and getSelectedIndex() that you can use in your event listener.
Here is an example:
if (e.getSource() == b1) {
switch(choice.getSelectedIndex()) {
case 0:
t3.setText(String.valueOf(n1 + n2));
break;
case 1:
t3.setText(String.valueOf(n1 - n2));
break;
case 2:
t3.setText(String.valueOf(n1 * n2));
break;
case 3:
t3.setText(String.valueOf(n1 / n2));
break;
}
}

Related

How do I convert this if-else statement into a switch statement in java?

The prompt is:
Convert the following if-else-if statement into a switch statement. Don’t rewrite the constants or variable definitions, just the if statement.
final char BLT = 'b';
final char VEGAN = 'v';
final char TUNA = 't';
final char ROAST_BEEF = 'r';
double price;
int sandwichType;
System.out.println("Enter sandwich type: ");
sandwichType = keyboard.nextLine().charAt(0);
if (sandwichType == VEGAN || sandwichType == TUNA) {
price = 3.99;
} else if (sandwichType == BLT) {
price = 4.19;
} else if (sandwichType == ROAST_BEEF) {
price = 4.99;
} else {
System.out.println("That's not a valid sandwich type.");
System.exit(0); // This ends the program
}
System.out.println("Your total is is $" + (price*1.0825));
My current code is this:
switch (sandwichType) {
case 1:System.out.println("The price is $" + (3.99*1.0825));
case 2: System.out.println("The price is $" + (4.19*1.0825));
case 3: System.out.println("The price is $" + (4.99*1.0825));
break;
You are forgetting breaks in between the switch cases. You also will want to use the char names of the different sandwiches instead of numbers. Finally, if none of the cases match the given sandwhichType, you'll want to have a default case, this would be essentially be your else statement from the previous code. The one tricky piece is the first case which accepts two different types which can be done by having a case followed by another case.
switch (sandwhichType)
{
case VEGAN:
case TUNA:
price = 3.99;
break;
case BLT:
price = 4.19;
break;
case ROAST_BEEF:
price = 4.99;
break;
default:
System.out.println("That's not a valid sandwich type.");
System.exit(0);
break;
}
System.out.println("Your total is is $" + (price*1.0825));
The cases should be options
case BLT:
You also need a default case
default:
break;
And break; after every case.

Get Scientific Buttons Clear Before New Value

This might be a duplicate to my other question: JavaFX Calculator Doesn't Clear After Answer
I've made a scientific calculator with Javafx/Java, but the "Scientific" buttons, such as tan, or cos, or square root have a problem clearing. The add, subtract, multiply, and divide buttons work fine.
Ex): Say I did 2 + 2, then pressed = and got 4. If I pressed another number, it would clear first, not just add onto the number like this: 45 But like this: 5 And if I pressed +/-/// button, it would clear the text area, too of course, so that the user could put in another number.
Ex) Say I did 16 , then pressed square root and got 4. If I pressed another number, it would just add onto the original number like this: 323 Not like this: 3 That's the problem with all the other scientific buttons, too.
I did trigger the same thing for the scientific/+, -, etc. to clear before a new value comes in after the answer, so I don't know the problem here.
else if(event.getSource() == cos)
{
data = Float.parseFloat(display.getText());
Double ans = Math.cos(Math.toRadians(data));
display.setText(String.valueOf(ans));
dot.setDisable(false);
if(event.getSource() != divide && event.getSource() != add && event.getSource() != multi && event.getSource() != minus && event.getSource() != pow && event.getSource() != mod)
{
start = true;
}
}
Here's the 'start' code:
private boolean start = false;
if(start)
{
data = Double.parseDouble(display.getText());
start = false;
}
And how I did it with the +, -, etc. buttons:
else if(event.getSource() == equals)
{
Double secondOperand = Double.parseDouble(display.getText());
dot.setDisable(false);
switch(operation)
{
case 1: //Addition
Double ans = data + secondOperand;
display.setText(String.valueOf(ans));
break;
case 2: //Subtraction
ans = data - secondOperand;
display.setText(String.valueOf(ans));
break;
case 3: //Multiplication
ans = data * secondOperand;
display.setText(String.valueOf(ans));
break;
case 4: //Division
ans = 0d;
try{
ans = data / secondOperand;
}catch(Exception ex){display.setText("Error");}
display.setText(String.valueOf(ans));
break;
case 5:
ans = data % secondOperand;
display.setText(String.valueOf(ans));
break;
case 6:
ans = Math.pow(data, secondOperand);
display.setText(String.valueOf(ans));
break;
}
operation = -1;
if(event.getSource() != divide && event.getSource() != add && event.getSource() != multi && event.getSource() != minus && event.getSource() != pow && event.getSource() != mod)
{
start = true;
}
}
I would expect that if I did 16, then pressed square root and got 4. If I pressed another number, it would clear first, then show the new value put in.
So I'm wondering if there was another way to clear that would work for the scientific buttons.
It was actually this line of code that I was missing:
display.setText("");
If I put it in 'start' method, the problem would be solved.

Take different actions depending on jTextField value

I have many more cases, but I'm wondering if there is a simpler way to do this. If the user enters 1 the program will convert from inches to cm, if the user enters 2, the program will convert from cm to feet, etc.
if (jTextField1.getText() == 1) {
InchesToCm();
} else if (jTextField1.getText() == 2) {
CmToFeet();
} else if (jTextField1.getText() == 3) {
MetresToYards();
} else if (jTextField1.getText() == 4) {
KmToMetres();
} else {
jLabel8.setText("Error, try again");
}
It depends on your definition of 'simpler' but you could use a switch statement. Like so:
switch(Integer.parseInt(jTextField1.getText())){
case 1:
InchesToCm();
break;
case 2:
CmToFeet();
break;
case 3:
MetresToYards();
break;
case 4:
KmToMetres();
break;
default:
jLabel8.setText("Error, try again");
break;
}
This way you don't have to use a chain of if statements but if it's simpler is up to you.
I hope this helps :)

Java Switch Statement: creating a calculator error

I was wondering if anyone can see what is wrong with my code. It works except that the program is not acknowledging my switch statement - I searched lots of questions but as I am a novice I am clearly missing something.
import java.util.Scanner;
class Calmlr1 {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
String anotherOption = "y", operatorOpt= "a";
int no1=0, no2=0;
double result= 0;
System.out.println ("Welcome to the online calculator! Let's begin...");
while (anotherOption.equalsIgnoreCase ("y")) {
System.out.println ("Please enter your 1st number: ");
no1 = input.nextInt();
System.out.println ("Please confirm your operator:\n1 = +\n2 = - \n3 = *\n4 = /");
operatorOpt = input.next ();
System.out.println ("Please enter your 2nd number: ");
no2 = input.nextInt();
switch(no1) {
case 1:
result=no1+no2;
break;
case 2:
result=no1-no2;
break;
case 3:
result=no1*no2;
break;
case 4:
result=no1/no2;
default:
result = 0 ;
break;
}
System.out.println("Your total calculation is: "+result);
System.out.println("Would you like to do another sum? y/n ");
anotherOption=input.next();
}
}
}
You should be using switch(operatorOpt). Right now you are switching on the first number.
You also need to change:
int operatorOpt= 0;
operatorOpt = input.nextInt();
That is, if you want to keep your switch statement the same. Please also see #Daniel Imms answer for an additional bug fix.
Try adding a break at the end of case 4
case 4:
result=no1/no2;
break;
EDIT J L's answer is the main issue, but this is another problem that will break division.
Your switch should be on the operatorOpt and not on no1.
Also, you're missing a break in the case 4. So, if you want to do a division, you'll get 0 as result.
The input from the user for operatorOpt should be done with input.nextLine(). Or, if you want to keep the same switch statement, with input.nextInt().
It should be like this:
switch(operatorOpt)
{
case "+":
result=no1+no2;
break;
case "-":
result=no1-no2;
break;
case "*":
result=no1*no2;
break;
case "/":
result=no1/no2;
break;
default:
result = 0 ;
break;
}
Your switch statement should be on "operatorOpt" and not on "no1" as you suppose to check the operator and based on that you want to do the calculation. However, you must use JDK1.7 to use String in Switch statement since previous versions of JDK do not support String Switch.
Also, you should use "break" in case 4.
Your switch should be on the operatorOpt and not on no1.
You can use like this
switch(operatorOpt)
{
case "+":
result=no1+no2;
break;
case "-":
result=no1-no2;
break;
case "*":
result=no1*no2;
break;
case "/":
result=no1/no2;
break;
default:
result = 0 ;
break;
}

Postfix calculator, how to deal with 3 numbers in a row?

Here is my code so far:
public class PostfixCalculator {
private Stack<Float> stack;
private float result;
private Boolean isOperator (char op){
boolean operator;
switch (op){
case '+':
case '-':
case '*':
case '/':
case '^':
operator = true;
break;
default:
operator = false;
break;}
return operator;
}
private Boolean isFunction (String func){
String[] functions = {"sin", "cos", "max"};
for (int i=0; i<functions.length; i++){
if (func.equals(functions[i]))
return true; }
return false;
}
private void computeOperator (float op1, float op2, char op){
switch (op){
case '+':
result = op1 + op2;
break;
case '-':
result = op1 - op2;
break;
case '/':
result = op1/op2;
break;
case '*':
result = op1 * op2;
break;
case '^':
result = (float) Math.pow(op1, op2);
break;
default:
break;
}
}
public float calculate(String expr) throws IllegalArgumentException {
result = 0;
String token;
Float makeit;
char operator;
float op1, op2, pushFloat;
StringTokenizer calc=new StringTokenizer(expr);
stack = new Stack<Float>();
while (calc.hasNextToken()){
token=calc.getNextToken();
operator=token.charAt(0);
if (!(this.isOperator(operator))){
if (this.isFunction(token)){
if (token.equals("sin")){
op1=stack.pop();
result = (float) Math.sin(op1);
stack.push(result);
}
else if (token.equals("cos")){
op1=stack.pop();
result = (float) Math.cos(op1);
stack.push(result);
}
else if (token.equals("max")){
op1=stack.pop();
op2=stack.pop();
result=Math.max(op1, op2);
stack.push(result);
}
}
else {
makeit = new Float(token);
pushFloat = makeit.floatValue();
stack.push(pushFloat);
}
}
else {
op1 = stack.pop();
op2 = stack.pop();
computeOperator (op1, op2, operator);
stack.push(result);
}
}
return stack.pop();
}
}
I think I have the basics of it down, but how do I deal with postfix calculations with three digits in a row or more, like for example '2 3 4 * -'? Any help would be appreciated. Thanks in advance!
Yep, a stack. And one can implement a simple stack easily with an array and a counter -- no real need to use a fancy class.
The array would be as large as the most deeply nested expression that you can handle (10 elements should be sufficient for virtually all "real" problems).
Push is update A[i] and increment i. Pop is decrement i and reference A[i]. "8 9 +" is push(8), push(9), pop the top two elements, add them, push the result. Note that operators are never pushed, only operands/results.
'2 3 4 * -' would be push(2), push(3), push(4), pop top two, multiply, push result, pop two, subtract, push result.
"7 6 + cos" would be push(7), push(6), pop two, add, push result, pop one, perform "cos", push result.
Error if you need to pop an element and the counter is zero (eg, "7 +" -- you'd want to pop twice but you can only pop once). Also an error if the user expresses "finished" and there is more than one element in the stack.
Always "display" your top element, as that's the last value pushed or the result.
For a calculator like this, you should use a stack. Every number is a push and every operation has a corresponding action.
st = []
while input:
if isanumber(input.next()): st.push(input.consume())
else: #its an operator
#note this may be wrong for operators that have a specific order
if(input.next() == "+"):
stack.push(stack.pop() + stack.pop())
# more operations
input.consume()
print(st)
And that would be the rough python to do it, in this instance I look ahead a single token before making a decision.
edit:
Probably should have read your code before posting, anyway you must always push back the computed number, also attempt to simplify your code into only "functions" and "numbers" making functions that perform both. Regex is also useful for this sort of thing, such as the http://www.cplusplus.com/reference/std/regex/.

Categories