Test if char array contains some letters - java
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}");
Related
Of the two constructers one works and the other doesn't when the argument is correct
i'm new to programming. i don't understand why one of the constructers I'm using to check for the validity of the characters of a string argument in the constructer does not work. the constructer should check if the entered string contains only characters G,C,A,T, else it throws an IllegalArgumentException. I tried using an array of characters to check for the validity of the string by using the toCharArray() method on the entered string. the constructer works for invalid strings, but not for valid strings. but another constructer i used works. please let me know why the first one doesn't. //this is the first constructer that doesn't work for me public class Fragment { private String nucleotideSequence; public Fragment(String nucleotides) throws IllegalArgumentException { char[] validityCheck = nucleotides.toCharArray(); int validityCounter = 0; for (char c : validityCheck) { if(c != 'G' || c != 'C' || c != 'A' || c != 'T') { validityCounter++; } } if (validityCounter != 0) { throw new IllegalArgumentException("Invalid characters present"); } nucleotideSequence = nucleotides; } } // this is the second constructer that works public class Fragment { private String nucleotideSequence; public Fragment(String nucleotides) throws IllegalArgumentException { boolean k = false; for(int i = 0; i < nucleotides.length(); i++){ char lol = nucleotides.charAt(i); if(lol=='A'||lol=='G'||lol=='C'||lol=='T'){ k = true; } else{ k = false; } if(k == false){ throw new IllegalArgumentException("Dosent work"); } nucleotideSequence = nucleotides; } } }
Your problem in the constructor that is not working is with the following 'if' statement: if(c != 'G' || c != 'C' || c != 'A' || c != 'T') This statement is always true. So the following: for (char c : validityCheck) { if(c != 'G' || c != 'C' || c != 'A' || c != 'T') { validityCounter++; } } equals: for (char c : validityCheck) { validityCounter++; } the correct statement would be if(c != 'G' && c != 'C' && c != 'A' && c != 'T') {
java. do not accept 0 as first input in a text field
I'm using Java and this part of my code is for entering age in a text field that only accepts numbers, back spaces and delete. How can I also tell the code to avoid accepting 0 if its the first character ? Thank you. Here is the code: private void tfAgeKeyTyped(java.awt.event.KeyEvent evt) { char c = evt.getKeyChar(); if(!(Character.isDigit(c)) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)){ evt.consume(); } }
Well you just need to check if your entered character isn't equal to 0 in your condition using c == '0' when the current input is empty: if((this.currentInput.isEmpty() && (!Character.isDigit(c) || c == '0')) || !(Character.isDigit(c)) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)){ evt.consume(); }
private void tfAgeKeyTyped(final java.awt.event.KeyEvent evt) { final char c = evt.getKeyChar(); // You need access to the current input to known if you are on the // first character or not. // Here I assume it exists as a private member variable. final boolean isFirstChar = this.currentInput.isEmpty(); final boolean isValidEvent = (Character.isDigit(c) && !(isFirstChar && c == '0')) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE); if (isValidEvent) { evt.consume(); } }
Java Character Array Errors
I'm making a method for translating characters into their corresponding numbers e.g. a=1, b=2 ... I've been recieving flak from the IDE about my declaration of the dictionary array. I've read the documentation and still have no idea how I would improve this. Thanks for all your responses in advance! :D EDIT: Formatting public static int charNumTrans(char toBeTranslated){ //Variable init int translated = 0; char guessedVariable; //Checking if between a and i if(toBeTranslated == 'a' || toBeTranslated == 'b' || toBeTranslated == 'c' || toBeTranslated == 'd' || toBeTranslated == 'e' || toBeTranslated == 'f' || toBeTranslated == 'g' || toBeTranslated == 'h' || toBeTranslated == 'i'){ //Checking to see which array to use char[] dictionary; dictionary = new char {'0','.','1','a','2','b','3','c','4','d','5','e','6','f','7','g','8','h','9','i'}; //chekcing between j and s }else if(toBeTranslated == 'j' ||toBeTranslated == 'k' ||toBeTranslated == 'l' ||toBeTranslated == 'm' ||toBeTranslated == 'n' || toBeTranslated == 'o' ||toBeTranslated == 'p' ||toBeTranslated == 'q' ||toBeTranslated == 'r' || toBeTranslated == 's'){//Checking to see if in between dictionary[10] = {'0','j','1','k','2','l','3','m','4','n','5','o','6','p','7','q','8','r','9','s'}; }else{//Everything else will be in this data set. char[] dictionary = {'0','t','1','u','2','v','3','w','4','x','5','y','6','z'}; } guessedVariable = dictionary[1]; while(dictionary[guessedVariable] != toBeTranslated){ guessedVariable +=2; } // Assigns letter minus one of array. e.g. b = dictionary[5]. This will then assign dictionary[4] to translated. translated = Character.getNumericValue(dictionary[guessedVariable-1]); return translated; }
First of all, you are not initializing your arrays outside of the if statements, meaning your code at the end won't be able to call the "dictionary" array. Second of all, the problem with using arrays in your scenario that you have different sized arrays. Third of all, in terms of how you are initializing the arrays, as people have pointed out, you need to create a new object that is correct for your data set e.g. new char[] {...}. To fully solve your problem, you might want to consider something like this (I have initialized all of the arrays in the simplest way possible using the same method to avoid confusion): public static int charNumTrans(char toBeTranslated){ //Variable init int translated = 0; char guessedVariable; //Checking if between a and i if(toBeTranslated == 'a' || toBeTranslated == 'b' || toBeTranslated == 'c' || toBeTranslated == 'd' || toBeTranslated == 'e' || toBeTranslated == 'f' || toBeTranslated == 'g' || toBeTranslated == 'h' || toBeTranslated == 'i'){ //Checking to see which array to use char[] dictionary = {'0','.','1','a','2','b','3','c','4','d','5','e','6','f','7','g','8','h','9','i'}; return findValue(dictionary); //checking between j and s }else if(toBeTranslated == 'j' ||toBeTranslated == 'k' ||toBeTranslated == 'l' ||toBeTranslated == 'm' ||toBeTranslated == 'n' || toBeTranslated == 'o' ||toBeTranslated == 'p' ||toBeTranslated == 'q' ||toBeTranslated == 'r' || toBeTranslated == 's'){//Checking to see if in between char[] dictionary = {'0','j','1','k','2','l','3','m','4','n','5','o','6','p','7','q','8','r','9','s'}; return findValue(dictionary); }else{//Everything else will be in this data set. char[] dictionary = {'0','t','1','u','2','v','3','w','4','x','5','y','6','z'}; return findValue(dictionary); } } public static int findValue(char[] dictionary){ guessedVariable = dictionary[1]; while(dictionary[guessedVariable] != toBeTranslated){ guessedVariable +=2; } // Assigns letter minus one of array. e.g. b = dictionary[5]. This will then assign dictionary[4] to translated. translated = Character.getNumericValue(dictionary[guessedVariable-1]); return translated; }
Change dictionary = new char {'0','.','1','a','2','b','3','c','4','d','5','e','6','f','7','g','8','h','9','i'}; to dictionary = new char[] {'0','.','1','a','2','b','3','c','4','d','5','e','6','f','7','g','8','h','9','i'};
For your array declaration, you are missing the [] when you assign the values to the array object you're creating - so, for example, change your declarations to this: char[] dictionary = new char[]{'0','t','1','u','2','v','3','w','4','x','5','y','6','z'}; Also, if you are trying to convert letters to numerical equivalents, may I suggest that you cast the char that you've passed to the function into an int, and then subtract 61 from this value? Reason being is that 61 corresponds to the position of the character 'a' on the Unicode character table, and would greatly simplify assigning a number to the letter that you pass in.
The if statement is redundant in Java
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
How to Check Every Letter as a String
I'm failing the following test case: #Test (timeout=3000) public void gatenot_0(){ GateNot g = new GateNot (new Wire("inw"), new Wire("outa")); g.feed("0"); boolean ans = g.propagate(); assertEquals(sigs1, g.read()); } which says "Invalid character" - Exception thrown by the following method: public static List <Signal> fromString(String inps) { List<Signal> values = new ArrayList<Signal>(); for(int i = 0; i < inps.length(); i++) { if(inps.charAt(i) != '1' && inps.charAt(i) != '0' && inps.charAt(i) != 'X' && inps.charAt(i) != 'x' && inps.charAt(i) != ' ' && inps.charAt(i) != '\t') throw new ExceptionLogicMalformedSignal(inps.charAt(0), "Invalid character!"); else if(inps.charAt(i) == '1') values.add(HI); else if(inps.charAt(i) == '0') values.add(LO); else if(inps.charAt(i) == 'X') values.add(X); else if(inps.charAt(i) == 'x') values.add(X); } return values; } Everytime I pass something including "0" or "1" it throws Exception So, should I check every letter of String inps as a String instead of charAt(). If yes, how should I check that? Thanks in advance.
To check every letter as a string you could use Character.toString(inps.charAt(i)) instead of just inps.charAt(i) I would recommend storing it in a variable for each iteration instead of calling many times. You could also do String.valueOf(inps.charAt(i)) There is a shortcut inps.charAt(i) + "" And yet another way: inps.substring(i, i + 1) Note that if you end of converting each letter to string, you should use the .equals method when comparing them. For more information about this, you can look at How to convert a char to a String?