I am getting a lightbulb on NetBeans saying "The if statement is redundant"
I want to know how these two are equal to one another
public boolean isVowel(char in)
{
char temp = Character.toLowerCase(in);
if (temp == 'a' || temp == 'e' || temp == 'i' || temp == 'o' || temp == 'u')
{
return true;
}
else
{
return false;
}
}
and
public boolean isVowel(char in)
{
char temp = Character.toLowerCase(in);
return temp == 'a' || temp == 'e' || temp == 'i' || temp == 'o' || temp == 'u';
}
I can see how it would return true if one of the vowels matches with temp. However, I am not seeing how it would return false. Would it simply just return false if none of the conditions are met?
Solved: I was looking at the problem the wrong way. For it to return false, each conditional statement would have to be false. Ideally it would return false if the return statement was equivalent to:
return false || false || false || false || false;
and true if any one condition is met
return false || false || false || false || true;
Thanks you guys, it really helped.
The two statements are identical.
int x = #; //user input
if (x==1) { //any condition resulting in a true or false
return true;
} else {
return false;
}
and
return (x==1); //same thing, returning true if true, false if false;
This expression:
(temp == 'a' || temp == 'e' || temp == 'i' || temp == 'o' || temp == 'u')
calculates a boolean value. An if-statement tests this value. So instead of testing this expression in the ireturning the boolean value in the if/else-clause you can just return it.
Edit you can just prove if your char is a vowel?
Do it this way:
public boolean isVowel(char in) {
return "aeiou".indexOf(Character.toLowerCase(in)) < 0;
}
The two are indeed identical (and the if statement is redundant) and here's why.
The == is an equality operator, which means that, if the left side matches the right side, it evaluates to true, otherwise it evaluates to false. The || is a conditional operator, meaning that, if the equality on the left hand side evaluates to false, it will check the right side to see if it evaluates to true (or, if left side evaluates to true, then the expression will evaluate to true, called short-circuiting). If all of them evaluate to false, then the entire expression will evaluate to false.
Therefore, the if statement as you have it essentially turns into:
if(<expression>==true) { //in the case that the conditional evaluates to true
return true;
}
else { //in the case the conditional evaluates to false
return false;
}
So, that can just be reduced down to expression, since it will evaluate to a boolean anyways.
return <expression> //will be true if true, false if false
There's more on this in the Oracle documentation
boolean isNumeric(char cc){
//begin // test if cc is numeric
return (
(cc == '0')
| (cc == '1')
| (cc == '2')
| (cc == '3')
| (cc == '4')
| (cc == '5')
| (cc == '6')
| (cc == '7')
| (cc == '8')
| (cc == '9') );
} // isNumeric
Related
I have a quick question. I want to make my code shorter and I'm wondering whether I can put in some way below checkboxes into loop. The sense of this part of code is to enable "Find" button in case when at least one of checkbox is selected. Thank you in advance for every tip.
if (checkBoxes[0].isSelected() == true || checkBoxes[1].isSelected() == true
|| checkBoxes[2].isSelected() == true || checkBoxes[3].isSelected() == true || checkBoxes[4].isSelected() == true
|| checkBoxes[5].isSelected() == true || checkBoxes[6].isSelected() == true || checkBoxes[7].isSelected() == true
|| checkBoxes[8].isSelected() == true || checkBoxes[9].isSelected() == true || checkBoxes[10].isSelected() == true
|| checkBoxes[11].isSelected() == true || checkBoxes[12].isSelected() == true || checkBoxes[13].isSelected() == true
|| checkBoxes[14].isSelected() == true || checkBoxes[15].isSelected() == true || checkBoxes[16].isSelected() == true
|| checkBoxes[17].isSelected() == true || checkBoxes[18].isSelected() == true || checkBoxes[19].isSelected() == true
|| checkBoxes[20].isSelected() == true || checkBoxes[21].isSelected() == true) {
button.setEnabled(true);
Of course you can :
boolean found = false;
for (int i = 0; i < checkBoxes.length && !found; i++) {
found = checkBoxes[i].isSelected();
}
if (found) {
button.setEnabled(true);
}
or you can avoid the boolean variable and break out of the loop when you find the first selected checkbox :
for (int i = 0; i < checkBoxes.length; i++) { // you can also replace this with enhanced
// for loop
if (checkBoxes[i].isSelected()) {
button.setEnabled(true);
break;
}
}
Why not to use stream?
if (Arrays.stream(checkBoxes).anyMatch(checkbox -> checkbox.isSelected())) {
button.setEnabled(true);
}
As you have an array of course you can use a loop.
Here is a version with an enhanced loop :
for (Checkbox checkBox : checkBoxes){
if (checkBox.isSelected()){
button.setEnabled(true);
break;
}
}
try this:
for(int i=0; i < checkBoxes.length; i++) {
if(checkBoxes[i].isSelected()) {
button.setEnabled(true);
break;
}
}
Boolean j = false;
for (byte i = 0; i <= 21)
if (checkBoxes[i].isSelected() == true) {
j = true;
break;
if (j == true) {
//your code
}
you van use this code
it is so easy
Check if string formed using stated set of rules or not. Generated using the following rules:
a. the string begins with an 'a'
b. each 'a' is followed by nothing or an 'a' or "bb"
c. each "bb" is followed by nothing or an 'a'
I tried the following code:
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String str = scn.nextLine();
boolean b = false;
if (str.charAt(0) == 'a') {
if (str.charAt(1) == 'b') {
if (str.charAt(2) == 'b') {
b = true;
} else
b = false;
} else
b = false;
} else
b = false;
System.out.println(b);
}
is the code all right...???
For input = aab the output should be false and for input =abba the output should be true.
This is my snippet:
def checkAB(str):
if len(str) == 0:
return True
if len(str) == 1:
if str == 'a':
return True
else:
return False
if str[0] == 'a':
return checkAB(str[1:])
elif str[0] == 'b':
if str[1] == 'b':
return checkAB(str[2:])
else:
return False
else:
return False
Try to read the boolean and print the output in string "true" or "false". In my case i made a mistake here by directly returning boolean value.
One more snippet:
def checkAB(str):
if (len(str) == 0):
return True
if (str[0] == 'a'):
if (len(str[1:]) > 1 and str[1:3] == 'bb'):
return checkAB(str[3:])
else:
return checkAB(str[1:])
else:
return False
I hope this helps you.
This is the recursive approach:
public static boolean checkAB(String s)
{
if (s.length()==0)
return true;
if (s.charAt(0) != 'a')
return false;
if (s.length() >= 3 && "abb".equals(s.substring(0,3)))
return checkAB(s.substring(3));
else
return checkAB(s.substring(1));
}
If regular expressions are allowed, the pattern (a+(bb)?)+ matches strings that follow the rule (And doesn't match strings that don't).
Otherwise, Your approach can't possibly work without some kind of loop, because the string aaaaaaaaaaa does match the pattern.
Consider the following method, which should handle it.
private static boolean stringMatches(String s) {
// Handle empty and null cases first.
if (s == null || s.isEmpty()) return false;
// So long as the string continues to match the pattern, keep stripping
// characters from it until it is empty. If you reach empty, it matches the pattern.
while (! s.isEmpty()) {
// If the first character isn't 'a', we don't match; return false.
if (s.charAt(0) != 'a') {
return false;
}
// Check for abb, if so strip all of that, otherwise strip just the a
if (s.length() >= 3 && "abb".equals(s.substring(0,3)) {
s = s.substring(3);
} else {
s = s.substring(1);
}
}
// Reached empty string, return true.
return true;
}
The following is my attempt at this code in c++
#include <bits/stdc++.h>
using namespace std;
void fastIO()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
}
bool checkAB(string input)
{
if (input.empty())
{
return true;
}
if (input.size() == 1)
{
if (input[0] == 'a')
{
return true;
}
else
return false;
}
if (input[0] == 'a')
{
return checkAB(input.substr(1));
}
if (input[0] == 'b' && input[1] == 'a')
{
return false;
}
else if (input[0] == 'b' && input[1] == 'b' && (input[2] == 'a' || input[2] == '\0'))
{
return checkAB(input.substr(2));
}
else
return false;
}
int main()
{
fastIO();
string input;
cin >> input;
// the following if statement is just to ensure that if the first charachter is not 'a' then don't proceed at all.
if (input[0] != 'a')
{
cout << "false";
}
else
{
cout << (checkAB(input.substr(1)) ? "true" : "false");
}
return 0;
}
I have a char[] that must be comprised of the letters : 'R', 'B', 'O', 'V', 'J', 'F', 'I', 'N'. I must check if the array contains only these letters and if not, I need to reintroduce the letters till it contains the correct letters.
I did this by a method (which is not working):
boolean validation=false;
if (choixJoueur.length != 4) {
validation=false;
} else {
for (int i = 0; i < 4; i++) {
if (choixJoueur[i] != 'R' || choixJoueur[i] != 'B'
|| choixJoueur[i] != 'O' || choixJoueur[i] != 'V'
|| choixJoueur[i] != 'J' || choixJoueur[i] != 'F'
|| choixJoueur[i] != 'I' || choixJoueur[i] != 'N')) {
validation=false;
} else
validation=true;
}
}
If I test it with RBVD the validation is (correctly) calculated as false, but if I try RBVO the validation is (incorrectly) false too.
Frakcool is right about the first part. You want to check that a character {is not R, AND it is not B, AND it is not O, AND ...}. Currently, you are checking if an individual character {is not R, OR is not B, OR is not O, OR ...}. This doesn't work because every character in existence will be either not R or not B.
You also have another problem which is that you are only effectively checking if the last character is one of those characters because for every character you reset the value of 'validation' without taking into consideration a past failure. In other words, if the first letter failed but the last letter passed, you just set validation to true even though it should be false. Instead, it's best to just start with true and set it to false whenever a failure condition is encountered, without ever setting it to true again.
import java.io.IOException;
public class Main
{
public static void main(String[] args) throws IOException
{
char[] choixJoueur = { 'R', 'B', 'V', 'O' };
boolean validation = true;
if (choixJoueur.length != 4)
validation = false;
else
{
for (int i = 0; i < 4; i++)
{
if (choixJoueur[i] != 'R' && choixJoueur[i] != 'B'
&& choixJoueur[i] != 'O' && choixJoueur[i] != 'V'
&& choixJoueur[i] != 'J' && choixJoueur[i] != 'F'
&& choixJoueur[i] != 'I' && choixJoueur[i] != 'N')
{
validation = false;
}
}
}
System.out.println(validation);
}
}
if (choixJoueur[i] != 'R' || choixJoueur[i] != 'B'
|| choixJoueur[i] != 'O' || choixJoueur[i] != 'V'
|| choixJoueur[i] != 'J' || choixJoueur[i] != 'F'
|| choixJoueur[i] != 'I' || choixJoueur[i] != 'N')) {
validation=false;
}else
validation=true;
}
Let's debug your code:
Your input for example: RBVD then:
R != R is false but R != B is true so validation = false
B != R is true so validation = false
V != R is true so validation = false
D != R is true so validation = false
You remain with false the same goes with your second input.
You might want to change || for && on your if validations to validate all of the possibilities.
Also, in case the validation is false, you might want to break the for-loop :) (Or that's my guess)
If changed to && this would be the debug:
R != R is false so validation = true
B != R is true but B != B is false so validation = true
V != R is true but V != V is false so validation = true
D != R is true and D is different from all of the rest of letters, so validation = false
On the other hand with RBVO
R != R is false so validation = true
B != R is true but B != B is false so validation = true
V != R is true but V != V is false so validation = true
O != R is true but O != O is false so validation = true
After all of that your if statement should be:
if (choixJoueur[i] != 'R' && choixJoueur[i] != 'B'
&& choixJoueur[i] != 'O' && choixJoueur[i] != 'V'
&& choixJoueur[i] != 'J' && choixJoueur[i] != 'F'
&& choixJoueur[i] != 'I' && choixJoueur[i] != 'N')) {
validation=false;
break; //because I guess if it contains any of the letters the validation fails, if you don't and the next letter is a valid one it will override validation to true.
}else
validation=true;
}
Also you can change it to:
boolean validate = true;
and remove the else statement inside your for-loop. But still take into consideration the break statement since it will prevent the program from doing more operations when it knows it's an invalid input from the moment it finds it's invalid (such as on 1st letter or something like that).
The problem is the logic; you should be using && (rather than ||) between your conditions (every character is not equal to at least one of the tested chars).
But you can simplify your code considerably by using regex, which does it all in one line:
boolean validation = new String(choixJoueur).matches("[RBOVJFIN]{4}");
If you want to also assert that no character is used more than once:
boolean validation = new String(choixJoueur).matches("((?!(.).*\\1)[RBOVJFIN]){4}");
I've tried tinkering around with this for awhile and have yet to figure out what its giving me this error. The code is far from complete but I'm just trying to figure out why it says it can't find variable ch1. Any help is greatly appreciated!
public class PhoneNumber {
String phoneNumber;
public PhoneNumber(String num) {
phoneNumber = num;
}
public String decodePhoneNumber() {
// Takes string form phone number and decodes based on number pad
// Find code that makes if statement not care about caps
// so if a || b || c number[cnt] = 1 etc..
for (int cnt = 0; cnt < phoneNumber.length(); cnt++) {
char ch1 = phoneNumber.charAt(cnt);
if (Character.ch1.equalsIgnoreCase("a") || ("b") || ("c")) {
} else if (ch1.equalsIgnoreCase("d" || "e" || "f")) {
} else if (ch1.equalsIgnoreCase("j" || "k" || "l")) {
} else if (ch1.equalsIgnoreCase("m" || "n" || "o")) {
} else if (ch1.equalsIgnoreCase("p" || "q" || "r" || "s")) {
} else if (ch1.equalsIgnoreCase("t" || "u" || "v")) {
} else {
}
}
}
}
You have syntax errors and that is why you cannot find ch1.
Try modifying your code as per this syntax. These changes need to be done in all the conditionals.
if ((ch1 == 'a') || (ch1 == 'b') || (ch1 =='c')) {
If you want to make it work regardless of capital letters then you would need to normalize the input to lower case and then do the character comparison:
char ch1 = phoneNumber.toLowerCase().charAt(cnt);
if (ch1 == 'a' || ch1 == 'b' || ch1 == 'c') {
// Do something
}
...
I'm trying to validate a hexadecimal number and its not going too well. I'm trying the code below but my logic isn't exactly on the ball. Any help?
if (!array[i].equals("A") || !array[i].equals("B") || !array[i].equals("C") || !array[i].equals("D") || !array[i].equals("E") || !array[i].equals("F"))
{
b[i] = false;
}
else
{
b[i] = true;
}
The aim of the above code is to give me a true or false value. True being the value is between A to F false being the value isn't between A to F.
if ((array[i]-'A') > 5)
b[i]=false;
else
b[i]=true;
Change all || to &&.
Right now your if condition always evaluates to true (since any string is not equal to either "A" or "B").
Alternatively, replace the whole construct with:
b[i] = array[i].equals("A") || array[i].equals("B") || array[i].equals("C") ||
array[i].equals("D") || array[i].equals("E") || array[i].equals("F");
if (array[i].equals("A") || array[i].equals("B") || array[i].equals("C") || array[i].equals("D") || array[i].equals("E") || array[i].equals("F"))
{ b[i] = true; }
else
{ b[i] = false; }
alternatively you could use a List and use .contains() as well.
List<String> hexchars = new ArrayList<String>();
hexchars.add("A");
hexchars.add("B");
hexchars.add("C");
hexchars.add("D");
hexchars.add("E");
hexchars.add("F");
return hexchars.contains("A");
But a regular expression would be the cleanest way to do this in the long run.