I've been getting an "illegal start of expression" error when trying to compile this for loop inside a if statement in java. Does anyone have any idea why?
if(letter.equals(" ") || letter == null ||for(String a: array){ letter.equals(a);})
Try
if( letter == null || letter.equals(" ") || checkArray(array, letter))
{
...
}
boolean checkArray(String[] arryay, String letter)
{
for(String a: array)
if(letter.equals(a))
return true;
return false;
}
Note: checking letter for null after you have already called equals() does not make too much sense; i've reordered those.
You cannot. Perhaps you should move the if statement into the for statement?
As rfausak said, a for statement does not return a boolean. You should have made that an answer by the way.
If you use a Set you could write:
if ( (letter.equals(" ")) || (letter == null) || (a.contains(letter)) ) {}
Well, that´s because you can not have a for loop within an if condition. It seems you want to see if the letter is within the array array; if so then you can do it with Apache commons-lang's ArrayUtils:
ArrayUtils.contains( array, letter );
This wont work because a for doesn't evaluate to a boolean. For readabilities sake you should extract that to a method anyway, good examples appear in other answers.
Other points, you should rejig your conditionals to not be susceptible to NullPointerExceptions
if (letter == null || " ".equals(letter) || arrayContains(array, letter)) {
//...
}
If you are able to add additional libraries, there are some nice apache commons libraries to make this work easier, namely StringUtils in commons-lang and CollectionUtils in commons-collections.
You also may like to harden that input checking if it's possible to get Strings larger than one character, by using String#trim() after checking for null. Again, this would be a good candidate for an extracted method isBlank(String str).
Related
I'm a beginner in coding. I was recently working with to create a chatting programme where a user will chat with my computer. Here is a part of the code:
System.out.println("Hello, what's our name? My name is " + answer4);
String a = scanner1.nextLine();
System.out.println("Ok, Hello, " + a + ", how was your day, good or bad?");
String b = scanner2.nextLine();
**if (b.equals("good"))** { //1
System.out.println("Thank goodness");
} else **if (b.equals("it was good"))** { //2
System.out.println("Thank goodness");
} else **if (b.equals("bad"))** { //3
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
} else **if (b.equals("it was bad"))**{ //4
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
if(age<18){System.out.println("How was school?");}
else if (age>=18){System.out.println("How was work?");}
The conditions of the if statements are in Bold (surrounded with **). In case of first and the second condition I want my application to do same thing. Similarly third and fourth condition. I thought it was possible to somehow group them in if statement.
I tried with below code but it doesn't compile:
if (b.equals("good"), b.equals("it was good")) {
System.out.println("Thank goodness");
} else if (b.equals("bad"),(b.equals("it was bad"))) {
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
Can someone correct it for me?
You can use logical operators to combine your boolean expressions.
&& is a logical and (both conditions need to be true)
|| is a logical or (at least one condition needs to be true)
^ is a xor (exactly one condition needs to be true)
(== compares objects by identity)
For example:
if (firstCondition && (secondCondition || thirdCondition)) {
...
}
There are also bitwise operators:
& is a bitwise and
| is a bitwise or
^ is a xor
They are mainly used when operating with bits and bytes. However there is another difference, let's take again a look at this expression:
firstCondition && (secondCondition || thirdCondition)
If you use the logical operators and firstCondition evaluates to false then Java will not compute the second or third condition as the result of the whole logical expression is already known to be false. However if you use the bitwise operators then Java will not stop and continue computing everything:
firstCondition & (secondCondition | thirdCondition)
Here are some common symbols used in everyday language and their programming analogues:
"," usually refers to "and" in everyday language. Thus, this would translate to the AND operator, &&, in Java.
"/" usually refers to "or" in everyday language. Thus, this would translate to the OR operator, ||, in Java.
"XOR" is simply "x || y but both cannot be true at the same time". This translates to x ^ y in Java.
In your code, you probably meant to use "or" (you just used the incorrect "incorrect solution" :p), so you should use "||" in the second code block for it to become identical to the first code block.
Hope this helped :)
You're looking for the "OR" operator - which is normally represented by a double pipe: ||
if (b.equals("good") || b.equals("it was good")) {
System.out.println("Thank goodness");
} else if (b.equals("bad") || b.equals("it was bad")) {
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
This is probably more answer than you need at this point. But, as several others already point out, you need the OR operator "||". There are a couple of points that nobody else has mentioned:
1) If (b.equals("good") || b.equals("it was good")) <-- If "b" is null here, you'll get a null pointer exception (NPE). If you are genuinely looking at hard-coded values, like you are here, then you can reverse the comparison. E.g.
if ("good".equals(b) || "it was good".equals(b))
The advantage of doing it this way is that the logic is precisely the same, but you'll never get an NPE, and the logic will work just how you expect.
2) Java uses "short-circuit" testing. Which in lay-terms means that Java stops testing conditions once it's sure of the result, even if all the conditions have not yet been tested. E.g.:
if((b != null) && (b.equals("good") || b.equals("it was good")))
You will not get an NPE in the code above because of short-circuit nature. If "b" is null, Java can be assured that no matter what the results of the next conditions, the answer will always be false. So it doesn't bother performing those tests.
Again, that's probably more information than you're prepared to deal with at this stage, but at some point in the near future the NPE of your test will bite you. :)
You can have two conditions if you use the double bars(||). They mean "Or". That means only ONE of your conditions has to be true for the loop to execute.
Something like this:
if(condition || otherCondition || anotherCondition) {
//code here
If you want all of conditions to be true use &&. This means that ALL conditions must be true in order for the loop to execute. if any one of them is false the loop will not execute.
Something like this:
if(condition && otherCondition && anotherCondition) {
//code here
You can also group conditions, if you want certain pairs of them to be true. something like:
if(condition || (otherCondition && anotherCondition)) {
//code here
There is a simpler way.
if (b.contains("good")) {
...
}
else if (b.contains("bad")) {
...
}
I'm trying to write a program that that will find if there's an equal number of odds and even numbers in a given one, it's working great but it want to use conditional operator instead of these 4 rows (the // rows),
I'm getting this:
Syntax error on token "%", invalid AssignmentOperator
Can someone tell me why? What's wrong?
while(number!=0) {
//if(number%2==0)
//even++;
//else
//odd++;
number%2==0 ? even++ : odd++;
number/=10;
}
number%2==0 ? even++ : odd++;
This is not a statement. The result of a ternary must be assigned to something:
int x = number % 2 == 0 ? even++ : odd++;
However, this is stylistically quite awkward. I would use an if-else (i.e., what you originally had) over this pattern. Here you've created a temporary variable that you're never going to reuse, for the sole purpose of using a ternary.
It requires a variable at the left side at where you can place the value after the condition.
int tmp = (number%2 == 0)?even++:odd++;
number%2==0 ? even++ : odd++;
This statement is not assigning any value to number.As per my knowledge its always recommended for use if-else instead of ternary operator.
Because, in ternary operator the false/else part is compulsory to write, where in if-else else/false part is optional.
while(number!=0) {
//if(number%2==0)
//even++;
//else
//odd++;
int temp= number%2==0 ? even++ : odd++;
number/=10;
}
Now, temp variable is holding the value .
Is there a way to make sure that the + plus operator is used to concatenate a String as opposed to being used as an arithmetic operator, for example this won't work because inGame is a boolean and e.getSource() == list is also a boolean.
System.out.println((e.getSource() == list) + inGame);
but
System.out.println(e.getSource() == list +""+ inGame);
this will, is there someway for the top example to work e.g. a way to tell the compiler to use the operator as concatenate operator as opposed to the arithmetic one ?
You could use a StringBuilder to concatenate your Strings (and other stuff) properly. After all, that's what internally Java does when you use the "+".
System.out.println(new StringBuilder().append(e.getSource() == list).append(inGame).toString());
You can use String.valueOf():
System.out.println(String.valueOf(e.getSource() == list) + String.valueOf(inGame));
Or, if you're just printing:
System.out.print(e.getSource() == list);
System.out.println(inGame);
Lastly, printf() is also an option:
System.out.printf("%b%b\n", e.getSource() == list, inGame);
This is useful if you're trying to print in more complicated formats.
I'm trying to do a "do while" loop with a nested if statement. I'm trying to compare two possible values for a String variable "word". If !word.equals "deeppan or thin" do something, else do something. But its not liking me using the or || comparator .. Any suggestions would be welcome.
do {
word = scan.next();
if ( !word.equalsIgnoreCase( "Deeppan" || "thin" ) ) {
System.out.print("Sorry you must specify a Deeppan or thin base, try again: ");
} else {
break;
}
} while ( true );
equalsIgnoreCase takes a single string argument, not a logical expression. You can combine them with || or && though:
if (!word.equalsIgnoreCase( "Deeppan") && !word.equalsIgnoreCase("thin" ))
You have to do it like this:
if (!word.equalsIgnoreCase("Deeppan") && !word.equalsIgnoreCase("thin")) {
Think about the || which i switched to &&, because the if should only be true, if the value is not the first AND not the second one!
This part is wrong, that's not how you use the boolean || operator, and anyway the logic is incorrect:
if (!word.equalsIgnoreCase("Deeppan" || "thin"))
It should be like this, comparison-operator-comparison, and notice the correct way to state the comparison for the effect you want to achieve:
if (!(word.equalsIgnoreCase("Deeppan") || word.equalsIgnoreCase("thin")))
Or equivalently, using De Morgan's laws (and easier to read and understand, IMHO):
if (!word.equalsIgnoreCase("Deeppan") && !word.equalsIgnoreCase("thin"))
You have a few issues going on. First:
"Deeppan" || "thin"
is attempting to use the boolean "OR" operator to compare two strings. The "OR" operator can only compare boolean results and returns a boolean that is the result of the comparison:
System.currentTimeMillis() == 123455667 || object.equals(this) // both sides are boolean results.
true || false // returns 'false'
But let's pretend for a second that "Deeppan" || "thin" is OK (remember, it isn't) and the compiler knows that you want to compare the two strings. It still leaves the issue that the OR operator returns a boolean result (true or false), which you are then attempting to pass into the method equalsIgnoreCase on the word variable. equalsIgnoreCase takes a String argument, not a boolean. This is the second compilation issue. As has been pointed out, what you need is to check for the conditions separately and OR the result to get the final boolean
if("Deeppan".equalsIgnoreCase(word) || "thin".equalsIgnoreCase(word)) {
// do something
}
("Deeppan" || "thin")
is a boolean expression. equalisIgnoreCase takes a string. Therefore you need to make two seperate calls and OR the (boolean) results
I've written the following if-statement in Java:
if(methodName.equals("set" + this.name) ||
isBoolean() ? methodName.equals("is" + this.name) :
methodName.equals("get" + this.name)) {
...
}
Is this a good practice to write such expressions in if, to separate state from condition? And can this expression be simplified?
I would change it to
if (methodName.equals("set" + this.name)
|| methodName.equals( (isBoolean() ? "is" : "get") + this.name)) {
...
}
Is it good practice? It's good if it makes it easier to read. It makes it easier to read if (1) it does and (2) the sort of person who'd be confused by it won't be reading it. Who's going to read it?
Wouldn't something like the following work?
if (methodName.equals("set" + this.name)
|| methodName.equals("get" + this.name)
|| (isBoolean() && methodName.equals("is" + this.name))) {
...
}
It's more readable than the way in which you used the ternary operator and certainly easier to understand. It also has the advantage that it can avoid an unnecessary method call to the isBoolean method (it has either 1, 2 or 4 method calls whereas yours always has either 1 or 3; the performance gain/loss is probably too minute to notice).
Also there's a similar question here titled "Is this a reasonable use of the ternary operator?" One user had the following to say:
The ternary operator is meant to
return a value.
IMO, it should not mutate state, and
the return value should be used.
In the other case, use if statements.
If statements are meant to execute
code blocs.
Do note that I included parentheses around the expression containing '&&' for readability. They aren't necessary because x && y is evaluated before m || n.
Whether you choose to use it is up to you, but I tend to avoid it in favour of readability.
I would be inclined to change it to
if (methodName.equals(setterForThis())
|| methodName.equals(getterForThis())) {
...
}
with some functions extracted:
private String setterForThis() {
return "set" + this.name;
}
private String getterForThis() {
return (isBoolean() ? "is" : "get") + this.name;
}
It's longer of course, but I'm not really into golf anyway.