How to do equality comparisons in an if-else block in Java? - java

I'm new to Java but I'm lost on the below code. It's not printing out the cost:
boolean Smart;
boolean Flat;
int smallsmart = 322;
int largesmart = 405;
void price(){
Scanner in = new Scanner(System.in);
System.out.printf("%nWhat Type of TV would you like Smart of Flat ??? ");//Prompts
boolean TV = in.next() != null;
System.out.println("What Size would you like 32 or 42 inch ?? ");//Prompts
int Size = in.nextInt();
if (TV = Smart && Size == 32){//start of if
System.out.println("The Price of your Tv is " + smallsmart);
} else if (TV = Smart & Size == 42){//start of if
System.out.println("The Price of your Tv is " + largesmart);
}

Smart will be false (default value of boolean)
In if and else if condition , you mentioned TV = Smart
Which will be false for both the conditions.
That's why it is no printing anything.
Please correct your code. TV == SMART

in.next() != null is always true.
Smart is always false since it has its default value.
So TV == Smart is also always false.
You want
String TV = in.next();
// ...
if (TV == "Smart" && ...
or
boolean smart = in.next() == "Smart";
// ...
if (smart && ...

boolean smart;
boolean flat;
int smallSmart = 322;
int largeSmart = 405;
void price(){
Scanner in = new Scanner(System.in);
System.out.println("What Type of TV would you like Smart of Flat ???");
String typeOfTv = in.nextLine().toLowerCase();
if(typeOfTv.equals("smart")) {
smart = true;
} else if(typeOfTv.equals("flat")) {
flat = true;
} else {
System.out.println("You have not selected an appropritate TV. Exiting...");
System.exit(0);
}
System.out.println("What Size would you like 32 or 42 inch ?? ");//Prompts
int size = in.nextInt();
if (smart && size == 32){//start of if
System.out.println("The Price of your Tv is " + smallSmart);
} else if (smart & size == 42){//start of if
System.out.println("The Price of your Tv is " + largeSmart);
}
}
First of all, I'd recommend you name variables with camel case convention.
Here you are assigning TV to Smart
TV = Smart
= is used to assign values to variables and == is used to compare.

You did not assign a value to both of Smart and Flat booleans.
1 equals sign = means assign new value.
2 equals signs mean compare the two values,
so TV = Smart actually means that you are assigning the value of Smart to your TV variable.
You should change it to if (TV == Smart)

There is several things that you should have in mind.
First, I advise you to learn about the Java naming convention. Your variables, per example, should be lower-case (smart instead of Smart). Here it is a link to an Oracle document about that: http://www.oracle.com/technetwork/java/codeconventions-135099.html
Second, there is a big difference between = and ==. The first it's an assignment, the second it's a comparation.
Third, the diference is not that big, but you shoul choose well between using just one & or two. In if statements its a bit of a deal. With one (&), it just means AND, with two (&&), it also means AND, with a tweak: It "short-circuits".
What is "short-circuits"? in resume it is math kicking in. In this case:
1 AND 'something' = 'something';
0 AND 'something' = 0 (With && will short-cricuit)
Shurt-circuit is good when in an if statment you whant to check if a certain variable is null BEFORE using it, to avoid throwing an NullPointerException. Like this:
if( variable != null && variable.isSomething() ) {
//do stuff
}
If the variable variable is null (therefore variable != null is false), it will short-circuit to false, and it won't throw an exception because it won't attempt to read an non-existing variable.
I advise you to always short-circuit evaluations.
The same thong happens with the OR function. You have the plain | and the short-circuit one ||. In this the math is:
0 OR 'something' = 'something'
1 OR 'something' = 1 (With || will short-cricuit)
Forth, be careful when writing things like boolean TV = in.next() != null;, in the case on Scanner (I'm certain of it) it will not return null, but it might return an empty String.
I hope I have helped.
Have a nice day. :)

Related

Java: If statement not working?

Awnsers below worked, thanks guys!
boolean Again = true;
while (Again = true)
{
String input = JOptionPane.showInputDialog(null, "Input Za Number");
try
{
int input2 = Integer.parseInt(input);
int R1 = 1;
int R2 = 1;
while (R2 < input2)
{
R1 = R1 * 2;
R2 = R2 + 1;
JOptionPane.showMessageDialog(null, R1);
}
String Ag = JOptionPane.showInputDialog(null, "Do it again? (Y/N)");
if (Ag.equals("N"))
{
Again = false;
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "What is '" + input + "'?!?! Enter an actual number.");
}
}
I put the part thats not working as I hope in bold. Its the "if (Ag.equals("N"))". Im trying to make it so if a user inputs "N", then the program will stop running. Otherwise it will loop and keep going. Problem is, even if I type N, it will loop. I am getting no errors. Please help, I am much confuse :(
This is a prime example as to why professional developers will always use
if ( null == object )
over
if ( object == null )
In the event of a mistype, such as the following
// as posted
while ( Again = true ) // works, always true
// the other way
while ( true = Again ) // compiler error
the way as posted would be reassigning the value true to Again every time the loop is reiterated; if the statement had been written the other way, the compiler would have thrown an error, stating that you can not assign a value to true.
With just the single equals, you are reassigning the value of Again to true every time you get here, where as the double equals checks for equality.
In a case such as this, you really don't even need the true, you could simply be using
while ( Again )
// or again
while ( true == Again )
relevant
When you do something like
while (Again = true)
you are actually assigning the variable to true,
that is making your while infinite...
Do instead
while (Again) // since is boolean you dont need to compare against a true value..

How would I ask java to stop until a variable is changed?

so I am trying to design a GUI with the program BlueJ, that sends data from a jtextfield box into a variable (already done), and using that variable to be able to update another variable, but for java to "stop running" until a specific variable is updated. So something along the lines of...
string bacon = "";
int agility = 1;
int dexterity = 2;
int strength = 3;
int intelligence = 4;
int charisma = 5;
//my variables.
if (bacon = "agility")
{
//what I am doing goes below where words are being used instead
Stop java progression until bacon is updated with an integer.
agility= agility+bacon
}
else if (bacon = "dexterity")
{
//what I am doing goes below where words are being used instead
Stop java progression until bacon is updated with an integer.
dexterity = dexterity+bacon
}
else if (bacon = "strength")
{
//what I am doing goes below where words are being used instead
Stop java progression until bacon is updated with an integer.
strength = strength+bacon
}
else if (bacon = "intelligence")
{
//what I am doing goes below where words are being used instead
Stop java progression until bacon is updated with an integer.
intelligence = intelligence+bacon
}
else if (bacon = "charisma")
{
//what I am doing goes below where words are being used instead
Stop java progression until bacon is updated with an integer.
charisma = charisma+bacon
}
Thank you very much to anybody who can help me figure this out. I would also like it to have something so that if bacon is stated as a non-integer (32.7 or "hello"), it would simply ask you to input a proper integer.
Not quite sure what you are asking in the first part of the question, but for the second part to it check if it is a non integer you can do something like this....
boolean isValidInput = true;
for(int i=0;i<bacon.length();i++) {
char charAt = bacon.charAt(i);
if(!Character.isDigit(charAt)) {
isValidInput = false;
break;
}
}
if(!isValidInput)
System.out.println("Invalid Input!");
Also, = is used for assignment in java, ex a = 3;, however if you are trying to check if something is equal to something else, you should use the == operator. ex. if(x==2)
But in your case, since you are comparing Strings, you should use if(x.equals("hello"))
Another tip, instead of saying charisma = charisma + bacon; you can just say charisma += bacon; as a shorthand ;)
Hope this helps,
Saashin

How should I format my return statement so I don't double the answer?

private String twoDigits(int value) {
String result = "";
{
if ((mMinute >= 0) && (mMinute <= 9) && (mSecond >= 0) && (mSecond <= 9)) {
tempmin = ("0" + mMinute );
tempsec = ("0" + mSecond );
} else
tempmin = (mMinute + "");
tempsec = (mSecond + " ");
return tempin+tempsec;
This just doubles the output that I'm looking for and I was wondering, whether or not the issue was with the return statement or the actual method.
I need to call back to this method, twoDigits(mMinute)+":"+twoDigits(mSecond) to get the code to display the time, but instead of being able to display 10:09:08 I keep displaying 10:0908:0908
I was wondering how I should fix my code.
Since there are a lot of tiny mistakes in your code, I'll suggest a slightly different approach. Not sure if this method works, in what I assume is Java, but give it a shot:
private String twoDigits(int value)
{
return value <= 9 ? "0" + value : value;
}
This is actually an if/else abbreviation. Return the following: If value <= 9 then add a zero before the value, else the value.
If there's a risk of negative values being received, you could add this:
return (value >= 0 && value <= 9) ? "0" + value : value;
First, there's Paul's comment about the {} after else to encompass both rows. Then, you are not actually using the value received by the function but rather some global variables (mMinute and mSecond). You create but never use result. Furthermore, your if statement says that if both mMinute AND mSecond are between 0 and 9 then both should be fixed. Since you should use value you only have to check that variable's range and edit it accordingly. On the row tempsec = (mSecond + " "); you add a space.. mistake? Finally, you misspelled tempmin on the return row.
Good luck.
Note that your method has a value parameter. You should use this rather than directly access the fields in your class. Perhaps it might help for you to think about the purpose of the twoDigits() method. It seems to me that it is supposed to take an int value and pad it with a leading zero if the input is only a single digit. Note that my description in the previous sentence does not refer to the member variables that represent minutes and seconds; it only refers to the input value.

Checking values in boolean array (Java)

I am having som slight difficulties with the following problem.
I have initialized a boolean array called numberArray with 31 indexes. The user is supposed to enter 5 digits between 1 and 30, and each time a digit is entered, the program is supposed to set the proper index to true. For instance, if I enter 5 then:
numberArray[5] = true;
However, if the user enters the value 5 a second time, a message should be given to the user that this number has already been entered, and so the user has to choose a different value. I have tried to create a loop as follows:
public void enterArrayValues() {
for(int i = 1; i < 6; i++) {
System.out.print("Give " + i + ". number: ");
int enteredNumber = input.nextInt();
while (numberArray[enteredNumber] = true) {
System.out.println("This number has already been chosen.");
System.out.print("Give " + i + ". number again: ");
enteredNumber = input.nextInt();
}
numberArray[enteredNumber] = true;
}
}
The problem is that when I run the program, I automatically get the message "The number has already been chosen" no matter what I enter. Even the first time I enter a number. I don't get this. Isn't all the values in the boolean array false by default?
I would greatly appreciate it if someone could help me with this!
while (numberArray[enteredNumber] = true) {
make that
while (numberArray[enteredNumber] == true) {
or change to
while (true == numberArray[enteredNumber]) {
or simply drop the ==true
while (numberArray[enteredNumber]) {
while (numberArray[enteredNumber] = true)
is an assignment, use the == operator or simply while (numberArray[enteredNumber]).
I know its hard to get into while you are still learning, but the earlier you start coding in an IDE the better off you will be. This is one tiny example of something an IDE will warn you about.
Change the while line to:
while (numberArray[enteredNumber]) {
Because mistakenly entering = instead of == is a common mistake, some people always code this type of statement in the following manner:
while (true == numberArray[enteredNumber]) {
With this format, if you use = instead of ==, you will get a compiler error.
Also, if you use a type of static analysis tool such as PMD, I believe you get a warning for the statement that you originally wrote.
Thde problem is in the condition of the while loop - you are using the assignment operator (=), whereas you are supposed to use the equality comparer (==). This way the loop condition is always true, because you are assigning true to the indexed field.
I hope this will work :-) .
The condition in the while loop should be while (numberArray[enteredNumber] == true). You're using the assignment operator =, not the comparison operator ==. Assignment is an expression that returns the assigned value, which is true in your case.

First Java program (calculator) problems

I'm in the process of learning Java and my first project is a calculator, however I've run into a snag. I'm trying to get my calculator to let me enter a number then click an operator (+, -, x, /), enter another number then hit an operator again and have the display update and be able to keep this going.
Example, I would like to be able to hit the following and have it display the total each time I hit an operator after the first:
a + b / c - d =
The code I have seems (to me) like it should work but it doesn't. What am I doing wrong?
The following is the code I'm using when you hit an operator. By default wait is set to false. After running through the class once, value1 is stored and wait is set to true and that works fine. From there it doesn't seem to work quite right:
class OperatorListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String input = event.getActionCommand();
// Set display as string
String s = display.getText();
if (!wait) {
// Convert first input string to double
try {
value1 = Double.valueOf(s.trim()).doubleValue();
} catch (NumberFormatException nfe) {
System.out.println("NumberFormatException: " + nfe.getMessage());
}
dec = false;
} else {
// Convert second input string to double
try {
value2 = Double.valueOf(s.trim()).doubleValue();
} catch (NumberFormatException nfe) {
System.out.println("NumberFormatException: " + nfe.getMessage());
}
// Determine operation to be performed
if (operator == "add") {
value1 = Operators.add(value1, value2);
} else if (operator == "subtract") {
value1 = Operators.subtract(value1, value2);
} else if (operator == "multiply") {
value1 = Operators.multiply(value1, value2);
} else if (operator == "divide") {
value1 = Operators.divide(value1, value2);
}
// Convert final value to string and display
display.setText(Double.toString(value1));
dec = false;
}
// Determine operator hit
if (input.equals("+")) {
operator = "add";
} else if (input.equals("-")) {
operator = "subtract";
} else if (input.equals("x")) {
operator = "multiply";
} else if (input.equals("/")) {
operator = "divide";
}
// Set wait
wait = true;
}
}
EDIT: Updated code to fix some confusion and update the if statement. Even after this the same problem still exists. Also, the full source is available here
A few suggestions.
First, I would suggest when using a boolean as a conditional for an if statement, avoid comparison with true and false -- there are only two states for boolean anyway. Also, since there are only two states, rather than using else if (false), an else will suffice:
if (condition == true)
{
// when condition is true
}
else if (condition == false)
{
// when condition is false
}
can be rewritten as:
if (condition)
{
// when condition is true
}
else
{
// when condition is false
}
Second, rather than comparing the string literals "add", "subtract" and such, try to use constants (final variables), or enums. Doing a String comparison such as (operator == "add") is performing a check to see whether the string literal "add" and the operator variable are both refering to the same object, not whether the values are the same. So under certain circumstances, you may have the operator set to "add" but the comparison may not be true because the string literal is refering to a separate object. A simple workaround would be:
final String operatorAdd = "add";
// ...
if (input.equals("+"))
operator = operatorAdd;
// ...
if (operator == operatorAdd)
// ...
Now, both the assignment of operator and the comparison of operator both are referecing the constant operatorAdd, so the comparison can use a == rather than a equals() method.
Third, as this seems like the type of calculator which doesn't really require two operands (i.e. operand1 + operand2), but rather a single operand which is acting upon a stored value (i.e. operand + currentValue), it probably would be easier to have some variable that holds the current value, and another variable that holds the operator, and a method which will act according to the current operator and operand. (More or less an idea of an accumulator machine, or 1-operand computer.)
The basic method of operation will be:
Set the currentValue.
Set the operator.
Set the operand.
Perform the calculation.
Set the currentValue to the result of the calculation.
Set the operator to blank state.
Each step should check that the previous step took place -- be sure that an operation is specified (operator is set to a valid operator), then the next value entered becomes the operand. A calculator is like a state machine, where going from one step to another must be performed in a certain order, or else it will not proceed to the next step.
So, the calculator may be like this (pseudocode!):
// Initialize calculator (Step 1)
currentValue = 0;
operand = 0;
operator = operatorNone;
loop
{
operand = getOperand(); // Step 2
operator = getOperator(); // Step 3
// Step 4 and 5
if (operator == operatorAdd)
currentValue += operand;
if (operator == operatorSubtract)
currentValue -= operand;
// ...
// Step 6
operator = operatorNone;
}
Although the above code uses a single loop and doesn't work like a event-based GUI model, but it should outline the steps that it takes to run a calculator.
Whenever you enter an operator, your code will execute this:
Double.valueOf(s.trim())
for setting either value1 or value2 (depending on wait). This will throw an exception because operators can't be parsed as doubles. You might have better luck checking for the operator first, before trying to parse the input as a number. Then if it was an operator, you can skip the number parsing part.
Also consider what might happen if somebody were to enter two numbers or two operators in a row.
As Greg said, no matter what the input and no matter what the current program state, you always parse out number. You need to track the program state more cleanly. I assume that when you code has "String s = output.getText();" that you really mean "String s = input.getText();".
Also note that
if (wait == false) {
// Stuff for !wait
} else if (wait == true) {
// Stuff for wait
}
is unnecessarily redundant. You can replace it with:
if (!wait) {
// Stuff for !wait
} else {
// Stuff for wait
}
You should probably check the input string to see if it is an operator, first, and if it isn't then make sure it is numeric. Writing an infix calculator (that properly handles precedence) is not trivial.
After searching high and low I finally determined that the problem didn't lie within the code I provided. I had had a "wait = false;" in my NumberListener class that was screwing up the execution. To solve this I created 2 separate wait variables and all is working fine so far.
Thanks for the help and the tips guys, +1 to all of you for trying.
You could use the scripting engine in Java. If you don't have Java 6+, you can use Rhino which does the same thing. You can then do pretty much anything you can do in JavaScript
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create a JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
// expose a, b, c, d
engine.put("a", 1);
engine.put("b", 8);
engine.put("c", 2);
engine.put("d", 3);
// evaluate JavaScript code from String
Number value = (Number) engine.eval("a + b / c * d");
System.out.println(value);
For more examples

Categories

Resources