IllegalStateException is not shown as wanted - java

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')

Related

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.

Missing Spaces in the Postfix expression output - Java

My code successfully converts an infix expression to postfix expression. However, when I enter a number that is more than 1 digit (e.g. 546) I get no spaces between this number and the right operand.
A test run of my code:
Input: Enter an expression: (24/4) / (15/3) * 10 - 4 + 2
Output: The Postfix Expression is: 244/ 153/ / 10 * 4 - 2+
I'd like it to be The Postfix Expression is: 24 4/ 15 3/ / 10 * 4 - 2+
This is my code: Please suggest any changes that will allow me to insert spaces in the output.
import java.util.*;
public class PostfixConversion {
public static void main(String args[]) {
System.out.print("Enter an expression: ");
String infix = new Scanner(System.in).nextLine();
System.out.println(convertToPostfix(infix));
}
public static boolean precedence(char first, char second)
{
int v1 = 0, v2 = 0;
//find value for first
if(first == '-' || first == '+'){
v1 = 1;
}else if(first == '*' || first == '/'){
v1 = 2;
}//end if
//find value for second
if(second == '-' || second == '+'){
v2 = 1;
}else if(second == '*' || second == '/'){
v2 = 2;
}//end if
if(v1 < v2){
return false;
}//end if
return true;
}//end precedence method
//converts infix expression into postfix expression
public static String convertToPostfix(String infixExp)
{
String postFix = "The Postfix Expression is: ";
Stack<Character> stack = new Stack<Character>();
char character = ' ';
for(int i = 0; i < infixExp.length(); i++)
{
character = infixExp.charAt(i);
//determine if character is an operator
if(character == '*' || character == '-' || character == '/' || character == '+')
{
while(!stack.empty() && precedence(stack.peek(), character)){
postFix += stack.pop();
}//end while
stack.push(character);
}
else if(character == '(') //check for left parenthesis
{
stack.push(character);
}
else if (character == ')')
{
while(!stack.peek().equals('(') && !stack.isEmpty()){ //add characters until left parenthesis
postFix += stack.pop();
}//end while
if(!stack.isEmpty() && stack.peek().equals('(')){
stack.pop(); // pop/remove left parenthesis
}
}
else
{
postFix += character;
}//end if
}//end for
while(!stack.empty()) //add the remaining elements of stack to postfix expression
{
if(stack.peek().equals('('))
{
postFix = "There is no matching right parenthesis.";
return postFix;
}
postFix += stack.pop();
}
return postFix;
}//end convertToPo
}
The fix is to add a line here (see code comment):
if(character == '*' || character == '-' || character == '/' || character == '+')
{
postFix += ' '; // <-- add space here
while(!stack.empty() && precedence(stack.peek(), character)){
postFix += stack.pop();
}//end while
stack.push(character);
}
after applying the fix the output on my machine looks like:
The Postfix Expression is: 24 4/ 15 3/ / 10 * 4 - 2+

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

Error "The operator == is undefined for the argument type(s) char, boolean"

I'm trying to do this:
System.out.println("Do you want to solve an equation (y/n)?");
char first = In.getChar();
boolean y = true;
boolean n = false;
if(first == y)
System.out.println("Enter a:");
if(first == n)
System.out.println("Thanks");
Basically, what I'm trying to do is that if I ask the user to solve the equation and the user presses y (meaning yes), then it will go through the if statement for which y is true; but if the user enters n (meaning no), then it will say something like "thanks for using the system".
I'm getting the error "The operator == is undefined for the argument type(s) char, boolean".
What am I doing wrong, and how can I fix this?
y is a boolean. 'y' is a char
if (first == 'y') {
...
}
You're comparing the different data types char and boolean and Java doesn't know how to do that. For example, what should be the result of this?
'a' == false
If you want to compare the content of a char variable with a specific char then do the following:
char charVar = 'n';
if (charVar == 'y') { // this would return "false", because 'n' is not equal 'y'
//...
}
So you can change your code as follows:
if(first == 'y')
System.out.println("Enter a:");
else if(first == 'n') // use "else if" instead of "if" :)
System.out.println("Thanks");

Parenthesis error check for infix to postfix conversion Java

I have been working on a program for infix to postfix conversion and have everything working except that I cannot figure out where to put an error check for a missing left parenthesis. Basically the user inputs a String and the program goes to this class and converts it but I want to make sure they have entered the correct amount of parenthesis. I have tried multiple places but keep coming up with EmptyStackExceptions.
import java.util.*;
public class PostfixConversion {
public static boolean precedence(char first, char second)
{
int v1 = 0, v2 = 0;
//find value for first
if(first == '-' || first == '+'){
v1 = 1;
}else if(first == '*' || first == '/'){
v1 = 2;
}//end if
//find value for second
if(second == '-' || second == '+'){
v2 = 1;
}else if(second == '*' || second == '/'){
v2 = 2;
}//end if
if(v1 < v2){
return false;
}//end if
return true;
}//end precedence method
//converts infix expression into postfix expression
public static String convertToPostfix(String infixExp)
{
String postFix = "The Postfix Expression is: ";
Stack<Character> stack = new Stack<Character>();
char character = ' ';
for(int i = 0; i < infixExp.length(); i++)
{
character = infixExp.charAt(i);
//determine if character is an operator
if(character == '*' || character == '-' || character == '/' || character == '+')
{
while(!stack.empty() && precedence(stack.peek(), character)){
postFix += stack.pop();
}//end while
stack.push(character);
}
else if(character == '(') //check for left parenthesis
{
stack.push(character);
}
else if (character == ')')
{
while(!stack.peek().equals('(') && !stack.isEmpty()){ //add characters until left parenthesis
postFix += stack.pop();
}//end while
if(!stack.isEmpty() && stack.peek().equals('(')){
stack.pop(); // pop/remove left parenthesis
}
}
else
{
postFix += character;
}//end if
}//end for
while(!stack.empty()) //add the remaining elements of stack to postfix expression
{
if(stack.peek().equals('('))
{
postFix = "There is no matching right parenthesis.";
return postFix;
}
postFix += stack.pop();
}
return postFix;
}//end convertToPostfix
}
First of all, you have to change your while loop to this form:
while (!stack.empty() && precedence(stack.peek(), character)) {
postFix += stack.pop();
}
i.e. change order of expressions in while's check: stack.empty() check should be the first.
Second fix will be addition of "There is no matching left parenthesis." error message here:
if (!stack.isEmpty() && stack.peek().equals('(')) {
stack.pop(); // pop/remove left parenthesis
} else {
postFix = "There is no matching left parenthesis.";
return postFix;
}

Categories