Get Scientific Buttons Clear Before New Value - java

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.

Related

AWT Choice in a calculator

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;
}
}

Java using return value from method for if else statements

I made a method in java that prints a menu screen that looks like this:
MENU
c - Number of whitespace characters
f - Find text
r - Replace all !'s
q - Quit
Choose an option:
The method returns a char. How do I use the return value of the method in main to make if else statements?
printMenu method:
public static char printMenu(Scanner scnr) {
char menuOp;
//display the menu
System.out.println("\nMENU");
System.out.println( "c - Number of whitespace characters");
System.out.println("f - Find text");
System.out.println("r - Replace all !\'s");
System.out.println("q - Quit\n");
menuOp = ' ';
//loop until the user has entered a c, f, r or q
while (menuOp != 'c' && menuOp != 'f' &&
menuOp != 'r' &&
menuOp != 'q') {
System.out.println( "Choose an option:");
menuOp = scnr.nextLine().charAt(0);
}
//return the letter that the user entered
return menuOp;
} //end of the printMenu method
What I want to be able to do in main:
while (return value from printMenu method != 'q'){
printMenu(scnr);
if (return value from printMenu method == 'c'){ //do this
}
else if (return value from printMenu method == 'f'){ //do this
}
else if (return value from printMenu method == 'r'){ //do this
}
}
}
I'm still new and really appreciate the help, patience, and kindness. Thanks
Edit - I have to use the return value from printMenu() as a requirement for a project.
This seems like a good example for using a do-while loop:
Scanner scanner = new Scanner(System.in);
char c;
do
{
c = printMenu(scanner);
switch (c)
{
case 'c':
//do something
break;
case 'f':
//do something
break;
case 'r':
//do something
break;
}
} while(c != 'q');
Answered by sweeper:
menuChar = printMenu(scnr);

Could you help me with my loop calculator?

I am making a calculator for school project. My problem is, that when I input e.g. 1 at op = sc.next().charAt(0);, the first if statement does its body, even if it's not true. Also, it doesn't return at the start of the loop, but the program ends. I'm still new at Java so that's why I'm here.
Also, I am open to any suggestions to make it better. :)
Thank you!
import java.util.Scanner;
public class Kalkulacka {
public static void main(String[] args) {
System.out.println("Vitajte v programe na výpočet jednoduchých matematických príkladov!");
Scanner sc= new Scanner(System.in);
double a;
char op = 0;
double b;
double priklad = 0;
int i=0;
System.out.println("Zadajte číslo");
a= sc.nextDouble();
priklad= a;
while (true) {
if (i<1) {
System.out.println("Zvoľte si operátora:");
System.out.println("1- +");
System.out.println("2- -");
System.out.println("3- *");
System.out.println("4- /");
op = sc.next().charAt(0);
if (op != 1 && op != 2 && op != 3 && op != 4) {
System.out.println("Zadali ste nesprávne číslo");
return;
}
}
if (i>=1) {
System.out.println("Zvoľte si operátora:");
System.out.println("1- +");
System.out.println("2- -");
System.out.println("3- *");
System.out.println("4- /");
System.out.println("5- =");
op= sc.next().charAt(0);
if (op!=1 && op!=2 && op!=3 && op!=4 && op!=5) {
System.out.println("Zadali ste nesprávne číslo");
return;
}
if (op==5) {
break;
}
}
System.out.println("Zadajte číslo");
b= sc.nextDouble();
if (i<1) {
switch (op) {
case 1:
priklad = a + b;
case 2:
priklad = a - b;
case 3:
priklad = a * b;
case 4:
priklad = a / b;
}
}
else {
switch (op) {
case 1:
priklad = priklad + b;
case 2:
priklad = priklad - b;
case 3:
priklad = priklad * b;
case 4:
priklad = priklad / b;
}
}
i=i++;
}
System.out.println("Výsledok je: "+priklad);
}
}```
A character is nothing but a number. That´s why you can compare a char with int as in your op != 1-check. However the appropriate number - the so-called ASCII-code - for '1' is not 1, but 49. 49 is surely not equal to 1, so your condition op != 1 matches.
Either check for op == 49 or just op == '1' (for the further checks you surely need the appropriate ASCII-codes 50, 51 and 52).
I think the problem is
op = sc.next().charAt(0);
if (op != 1 && op != 2 && op != 3 && op != 4) {
System.out.println("Zadali ste nesprávne číslo");
return;
}
Op is a char, so when you get the input from the user it's '1', '2', '3', '4' but you check equality with 1, 2, 3, 4. Condition is always true and the program returns.
My problem is, that when I input e.g. 1 at op = sc.next().charAt(0);,
the first if statement does its body, even if it's not true.
Replace
if (op != 1 && op != 2 && op != 3 && op != 4)
with
if (op != '1' && op != '2' && op != '3' && op != '4')
as you are comparing char values. If you want to compare with their ASCII values, you can use op != 49 and so on. Check https://ee.hawaii.edu/~tep/EE160/Book/chap4/subsection2.1.1.1.html
The same applies to your switch...case also i.e. you should use case '1' instead of case 1.
Also, it doesn't return at the start of the loop, but the program
ends.
Replace return with continue.

Calling an Integer into a Boolean

The section of my code that isn't working
}else if(bossOne == 3){
int bossOneHP = 70 + bossStat.nextInt(10)-5;
int bossOneOP = 27 + bossStat.nextInt(10)-5;
int bossOneBP = 12 + bossStat.nextInt(10)-5;
String bossName = "Spartan King";
waits();
System.out.println("Your first enemy is the Spartan King.");
System.out.println("It has a very powerful attack, lets hope you have enough health.");
}
boolean keepPlaying = true;
while (keepPlaying){
Scanner choice = new Scanner(System.in);
System.out.println("Enter 1 to attack.");
System.out.println("Enter 2 to block.");
System.out.println("Enter 3 to exit the game.");
int selection = choice.nextInt();
if (selection == 1){
waits();
System.out.println("You attack.");
System.out.println(bossOneHP == bossOneHP - (OP - bossOneBP));
}else if(selection == 2){
waits();
System.out.println("You block.");
System.out.println(HP == HP - (bossOneOP - BP));
}else if(selection == 3){
break;
}
if (bossHP == (0 || >0){
System.out.println("Congratulations you won!");
break;
}
if (HP == (0 || >0)){
System.out.println("Sorry you lost.");
break;
}
I need to have the integers be called to the section. This code is for the meat of the game I am creating for my programming class any help would be appreciated.
You want the 'greater than or equal to' operator: >=
if (bossHP >= 0){
System.out.println("Congratulations you won!");
break;
}
if (HP >= 0){
System.out.println("Sorry you lost.");
break;
}
OK, so I'm not sure exactly what is supposed to do what but I will give it a try. It looks like you got a little confused.
For example:
if (selection == 1){
waits();
System.out.println("You attack.");
System.out.println(bossOneHP == bossOneHP - (OP - bossOneBP));
}else if(selection == 2){
In this code you seem to be printing to console a comparison of the variable bossOneHP and bossOneHP - (OP - bossOneBP), which I think is not what you intended as the statement would print true only if (OP-bossOneBP) was zero (basic algebra). What I suspected you intended:
if (selection == 1){
waits();
System.out.println("You attack.");
bossOneHP = bossOneHP - (OP - bossOneBP);
}else if(selection == 2){
This sets the variable bossOneHP to itself minus (OP minus bossOneBP). Note you can also do it like this:
if (selection == 1){
waits();
System.out.println("You attack.");
bossOneHP-= OP - bossOneBP;
}else if(selection == 2){
Which is faster. -= sets a value to itself minus the following value as opposed to = which just sets it to the new value. Also == does a comparison returning true if they are equal while = sets a variable to a new value.
Second issue:
if (bossHP == (0 || >0){
I am assuming you want to activate the if statement if bossHP is less than or equal to zero. The || statement is a boolean operator (It compares the two boolean inputs on either side, whether that be a variable or a comparison or a function, and returns a single boolean value of true if either input was true), and does not function like the word or. To compare two numbers (in this case the variable bossHP and zero), you use one of several operators. They are as follows:
== -returns true (which activates the if statement) if the numbers or objects (if they are the same instance, not if they contain equal values) on both sides are identical.
< -returns true if the left hand number is smaller than the right hand one (doesn't work on objects)
> -returns true if the right hand number is smaller
<= -returns true if the left hand number is smaller or equal to the right hand number
>= -returns true if the right hand number is smaller or equal to the left hand number
!= -returns true if the numbers or objects do not equal each other (effective opposite of the == token)
! -only takes one boolean on the right hand side and returns its opposite (this inverts the value essentially), if(!val) is equivalent and better to if(val == false)
The correct code would probably be something along the lines of:
if (bossHP >= 0){
System.out.println("Congratulations you won!");
break;
}
also instead of doing the while(keepPlaying) thing you could also do while(true) and run a break; command when 3 is inputed

IllegalStateException is not shown as wanted

I am trying out this little calculator program. When I call calculateResult() method, I want to show IllegalStateException error when the secondOperand is zero and the operator is division. But even though, I put an if clause in the calculateResult() to show this error, I don't get the error, but I get infinity. How should I change my code to show this error? Below is my code.
public double calculateResult() {
if (firstOperand != Double.NaN && secondOperand != Double.NaN && operator == '+') {
return firstOperand + secondOperand;
}
else if (firstOperand != Double.NaN && secondOperand != Double.NaN && operator == '-') {
return firstOperand - secondOperand;
}
else if (firstOperand != Double.NaN && secondOperand != Double.NaN && operator == '*') {
return firstOperand * secondOperand;
}
else if (firstOperand != Double.NaN && secondOperand != Double.NaN && operator == '/') {
return firstOperand / secondOperand;
}
else if (firstOperand != Double.NaN && secondOperand != Double.NaN && operator == '%') {
return firstOperand % secondOperand;
}
else if (secondOperand == '0' || operator == '/'){
throw new IllegalStateException ("Cannot divided by zero"); //this error never comes up when I print out calcualteResult() method.
}else {
return Double.NaN;
}
}
public static void main(String[] args) {
// main method
Calculator first = new Calculator();
first.setFirstOperand(5.0);
first.setSecondOperand(0);
first.setOperator('/');
first.calculateResult(); // I get [5.0 / 0.0 = Infinity] here...
System.out.println(first);
You haven't posted the actual code in question, so I can't say for sure, but there are two problems with the zero-detection specifically. First, you're comparing what is either a Double or a double with a char of value '0', not 0. Remove the single quotes around the numeric value. Additionally, checking for invalid inputs needs to happen before you evaluate the operation! If the operator is '/' (or '%'), you need to check for zero before dividing.
This code is a serious mess, and it's simple enough that I'll show how it should be written if you have to use a character for operator (something like an enum is nearly always a better choice).
public double calculateResult() {
// check in one place instead of duplicating
if(Double.isNaN(first) || Double.isNaN(second))
return Double.NaN;
// check preconditions *before* calculating
if(second == 0.0 && (operator == '/' || operator == '%'))
throw new IllegalStateException("explanation");
switch(operator) {
case '+': return first + second;
case '-': return first - second;
case '*': return first * second;
case '/': return first / second;
case '%': return first % second;
default: return new IllegalStateException("unsupported operation");
}
}
If secondOperand is zero and operator is '/', an earlier check will pass, do the computation, and return the properly computed infinity value:
else if (firstOperand != Double.NaN && secondOperand != Double.NaN && operator == '/') {
return firstOperand / secondOperand;
}
As has been noted in other answers and comments, some of your code (including this snippet) is wrong in other ways.
You should be using Double.isNan(operand) to test whether something is NaN, as NaN equality rules are a bit strange. And finally, you don't want to check a double and a character for equality.
But if you want to handle division by zero specially, you need to check for it before other conditions that it also meets.
else if (secondOperand == 0 && operator == '/'){ ... }
You're trying to compare a double value with char ('0')

Categories