Trying to add Conditional Statemnt [duplicate] - java

This question already has answers here:
I keep getting a "The operator == is undefined for the argument type(s) boolean, int" and have no idea how to fix it
(2 answers)
Closed 3 years ago.
I'm new to coding so sorry if this is a stupid question.
Why isn't the following code working?
I currently have int x = 100 and boolean b = false
if ( x == b)
{
System.out.println(x + " is equal to " + b);
}
else
{
System.out.println(x + "is not equal to " + b);
}
I expect the output to be "100 is not equal to false"

Sorry, late in the day. Got my logic backwards twice.
A 1 or any positive integer will be true. Think binary - 0 or 1.
The comparison is Boolean so 1 or 100 = true.

Related

String not getting printed in the output [duplicate]

This question already has answers here:
Getting strange output when printing result of a string comparison
(3 answers)
String equals and == with String concatenation [duplicate]
(4 answers)
Java string == Vs Equals giving true or false when combined with concatenation [duplicate]
(5 answers)
String concatenation and comparison gives unexpected result in println statement
(5 answers)
The expressions which evaluate to a boolean value can not be concatenated with a String in Java. Why? [duplicate]
(5 answers)
Closed 2 years ago.
String r1 = "hello";
String r2 = "hello";
System.out.println("Result: " + r1 == r2);
I tried running this code and i am not getting the String output in the console. The only value getting printed is the r1==r2 result i.e false.
The question here is I am expecting the output to be "Result: false" and why is false just getting printed.
Also i understand that .equals should be used, I just wanted to know why the result is such in the given scenario.
It would be great if some one can point to relevant documentation and help why this is the behaviour.
Indeed the output is "false" because first the concatenation is done so it is "Result: hello" and then it is compared to r2 ("hello") which returns false.
That's why you see "false" in console.
If you want to see "Result: true" you need to use equals instead of == because that's how we compare Strings in java. See below post to understand differences:
How do I compare strings in Java?
If you really want to compare them using "==" you need to add brackets so the comparison will be first before concatenation.
String r1 = "hello";
String r2 = "hello";
System.out.println("Result: " + r1 == r2); // output: "false"
System.out.println("Result: " + r1.equals(r2)); // output: "Result: true"
System.out.println("Result: " + (r1 == r2)); // output: "Result: true"
Because it was processed as
("Result: " + r1 ) == r2
which is false. It was processed in this way because + has a higher priority than ==.
What you need to do to get the string as well is
System.out.println("Result: " + (r1 == r2));
which will give you Result: true
To compare strings and print the way you want you should use method equals(). Like this:
String r1 = "hello";
String r2 = "hello";
System.out.println("Result: " + r1.equals(r2));

Java If Else Text Based on Other Text [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I am trying to have a text-box populate with X if another text-box has a certain value, else Y. However, it's populating with X or Y seemingly randomly. d4 is my button, d4result is where it populates the result, d4txt1 is where I want to see a 1 or 0, depending.
d4.setOnClickListener {
if (d4result.text.toString() == "1") {
d4txt1.text = "1"
} else {
d4txt1.text = "0"
}
val rand = Random().nextInt(4) + 1
d4result.text = rand.toString()
}
So if d4result is populated with 1, I want d4txt1 to populate with 1, otherwise it should be zero. But when I try it, I get 1 or 0 and I can't notice a pattern as to when/why.
Use equals instead of ==. == operator will return true only if two object reference it is comparing represent exactly same object otherwise "==" will return false.
d4.setOnClickListener {
if (d4result.text.toString().equalsIgnoreCase("1")) {
d4txt1.text = "1"
} else {
d4txt1.text = "0"
}
val rand = Random().nextInt(4) + 1
d4result.text = rand.toString()
}
Java is tricky about that. The == operator compares the two object pointers, not their values. It's fine for integers and floats but almost never useful for strings.
Instead use the .equals() method or the .equalsIgnoreCase() method:
if (d4result.text.toString().equalsIgnoreCase("1")) { ...

what does "0" stand for in conditional operator? [duplicate]

This question already has answers here:
Ternary Operator
(4 answers)
Closed 4 years ago.
Consider the following code:
i = (i == array.length-1) ? 0 : i + 1;
As I understand, the conditional operator works as follows:
booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse
What does 0 execute?
I do not think the "positive conditional test result" really has a formal name.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html
?: Ternary (shorthand for
if-then-else statement)
using a boolean example
isConditionTrue = 1 == 2 ? true : false;
this in your example
i = (i == array.length-1) ? 0 : i + 1;
has the same result as
if (i == array.length-1)
{i= 0 ;}
else {i = i + 1;}
This is known as the Elvis Operator (see [https://en.wikipedia.org/wiki/Elvis_operator]) and given the following example:
x = A ? B : C;
... it means that if A is evaluated to 'true' than x gets assigned the value B otherwise it gets assigned the value C.
In your example it means, that if 'i==array.length-1' then 'i' is set to '0' otherwise 'i' is set to 'i+1'.

What does the "?" key do in Java? [duplicate]

This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 8 years ago.
I've been trying to Google it, but googling the key "?" doesn't really work out that good.
I really want to know what it does and when to use it.
Thanks!
I've seen it a couple times, but here is an example of one I just saw
String name = perms.calculateRank().getColor() + player.getName();
//This is a custom ranking system ^
player.setPlayerListName(name.length() > 15 ? name.substring(0, 16) : name);
player.setDisplayName(name + ChatColor.RESET);
Chat.sendMessage(player, "Tab Name Set");
This is a ternary operator. In Java specifically, it is called the Conditional Operator. It is a way of writing short-hand simple if..else statements. For example:
if (a == b) {
c = 123;
} else {
c = 456;
}
is the same as:
c = a == b ? 123 : 456;
It is also used for a wildcard generic.
public List<?> getBizarreList();
The ternary operator someBoolean ? x : y evaluates to x if someBoolean is true, and y otherwise.
It is called ternary operator and it is only operator that takes 3 operands. In better sense, it is conditional operator that represent shorter format
General Syntax :
boolean expression ? value1 : value2
your example:
player.setPlayerListName(name.length() > 15 ? name.substring(0, 16) : name);
as same as
if( name.length() > 15)
player.setPlayerListName(name.substring(0, 16));
else
player.setPlayerListName(name);

Taking info from a file and parsing through to get the equations from it [duplicate]

This question already has answers here:
How to evaluate a math expression given in string form?
(26 answers)
Closed 9 years ago.
wIt's very confusing, I know, but essentially what I am trying to figure out is how to take the information from a file and parse through it in order to get the equations in the file.
Like say, the file contains the problem 8 + 5 = 13
I want my program to read the file and then take the integers 8 and 5, recognize the operator symbol, and then do the math so that it can compare it to the final answer in order to grade the problem.
I have these lines of code already, which can capture the first integer, but I'm stuck on getting the operator and the second integer so that I can get the program to do the math.
int whiteSpace1 = fileContent.indexOf(" ");
int first = Integer.parseInt(fileContent.substring(0, whiteSpace1));
int second = Integer.parseInt(fileContent.substring(whiteSpace1, 2));
I have no real clue where to go from here in order to get the operator and second int.
Please help.
Extra Info: There will not always be just two operands and they won't always be ints.
I also cannot use arrays or regex or a try/catch.
For simple expression parsing, consider using StreamTokenizer.
Simple example code snippet to see how it works:
StreamTokenizer tokenizer = new StreamTokeniner(new StringReader(fileContent));
while (tokenizer.nextToken() == Tokenizer.TT_EOF) {
if (tokenizer.ttype > 32) {
System.out.print("token type: '" + ((char) tokenizer.ttype) + "'");
} else {
System.out.print("token type: " + tokenizer.ttype);
}
System.out.println(" string value: " + tokenizer.sval +
" numeric value: " + tokenizer.nval);
}

Categories