if(input.charAt(i) == '0' || input.charAt(i) == '1' || input.charAt(i) == '2') {
}
Is there a way to condense this if condition, or no?
You could check if the character matches any index in a common String. Like,
if ("012".indexOf(input.charAt(i)) > -1) {
}
Maybe a little more readable (in java 9+)
if (Set.of('0', '1', '2').contains(input.charAt(i))) {
}
You can make it shorter by assigning the character lookup result in a variable (but still three equality checks).
char c = input.charAt(i);
if(c == '0' || c == '1' || c == '2') {
}
You can look at the other answers like creating a Set/Array and doing the contains check if the number of equality checks will increase in the future. IMO, three checks should be fine to be written as is.
Related
What could be an efficient way to check a character is alphabet or not?
Using
Character.isLetter(ch)
(or)
if( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
Checking for A-Z a-z does not check all alphabetic characters. so the question seems moot.
Character.isAlphabetic(c) tests whether c is alphabetic.
Character.isLetter(c) tests whether c is a letter.
The two are not equivalent so you should be clear on the question you're trying to answer. The difference is that there are number-indications that are alphabetic but not letters; think Roman numerals. Link to list.
//function to check whether given character is an alphabet or not
function check(n){
var a=(+n); //If unary operator operates on a string then we get NaN.
if(isNaN(a)){ //Checking if a is NaN
console.log("This is a alphabet")
}
else{
console.log("Is a number")
}
}
check(12)
check("a");
I want to check if the char is null or not? but why this code is not working? letterChar == null also is not working. I googled for many problems but didn't see any solutions, mostly the solutions are about String.
String letter = enterletter.getText().toString();
char letterChar = letter.charAt(0);
if(letterChar == ' ' || letterChar == NULL) // this is where the code won't works
{
Toast.makeText(getApplicationContext(), "Please enter a letter!", Toast.LENGTH_LONG).show();
}
A char cannot be null as it is a primitive so you cannot check if it equals null, you will have to find a workaround.
Also did you want to check if letterChar == ' ' a space or an empty string? Since you have a space there.
The first two answers here may be helpful for how you can either check if String letter is null first.
or cast char letterChar into an int and check if it equals 0 since the default value of a char is \u0000- (the nul character on the ascii table, not the null reference which is what you are checking for when you say letterChar == null)- which when cast will be 0.
char is a primitive datatype so can not be used to check null.
For your case you can check like this.
if (letterChar == 0) //will be checked implicitly
{
System.out.println("null");
}
//or use this
if (letterChar == '\0')
{
System.out.println("null");
}
From your code it seems like you work with Unicode and the method you search for is into Character class (java.lang)
Character.isLetter(ch);
It also contains lots of useful static method that can suite you.
If so, the code will be
String letter = enterletter.getText().toString();
char letterChar = letter.charAt(0);
if(!Character.isLetter(letterChar))
{
Toast.makeText(getApplicationContext(), "Please enter a letter!", Toast.LENGTH_LONG).show();
}
But if I would need to answer your question (without taking a look to your aim), then the code you need depends on what do you mean by "is char null".
In Java char cannot be == null.
If you want to check if it is not an empty space, you need to do
if (ch == ' ')
If you want to check if there are no line breakers (space, HT, VT, CR, NL and other), you should add the following to the proposed above:
if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '\x0b')
Right now, I have the code written that is displayed below:
if(letterTwo.equals("a" || "e" || "i" || "o" || "u") && !"a" || "e" || "i" || "o" || "u".equals(letterOne));{}
The errors I am receiving are:
"The operator ! is undefined for the argument types string", and "The operator || is undefined for the argument types string, java.lang,string, java.lang.string"
I was wondering how I could fix this code, and what the operators are used for comparing strings like I need to.
Assumption: letterTwo is a String
letterTwo.equals() expects a single String argument. Not the big boolean expression you are passing it.
You can either do
if (letterTwo.equals("a") || letterTwo.equals("b") || letterTwo.equals("c"))
{
//etc
}
Or if your Java version is new enough you may be able to use a switch
switch(letterTwo)
{
case "a":
case "b":
case "c": // stuff
break;
}
If letterTwo is actually a char (which it may well be given the name...), you can do similar things but it is a bit easier:
if (letterTwo == 'a' || letterTwo == 'b' || letterTwo == 'c')
{
//etc
}
Simple:
if (letter.equals("a") || letter.equals("b")
And so on. The point is that you have to use those boolean operators on expressions that have type boolean!
But of course, code as the above turns unreadable quickly. In the real world, such kind of checks would rather be done using a simple regular expression.
The correct way for you would be :
if( (letterTwo.equals("a") || letterTwo.equals("e") || letterTwo.equals("i") || letterTwo.equals("o") || letterTwo.equals("u")) && !(letterOne.equals("a") || letterOne.equals("e") || letterOne.equals("i") ||letterOne.equals("o") || letterOne.equals("u")) ;{}
Please note, this is not case-sensitive. It would treat "A" and "a" differently.If you want them to be treated in same way use "equalsIgnoreCase" instead of "equals" above.
As pointed out by #GhostCat above, it distrubs readability and regex should be much better to handle such cases
How find if the first three characters in a char[] seqarr are A/a, T/t, G/g in this order (case insensitive) in Java
I tried this
for(int i = 0; i <= 2; i++){
if(seqarr[i] == 'A'|| seqarr[i] == 'a' ||seqarr[i] == 'T' ||seqarr[i] == 't'|| seqarr[i] == 'G'|| seqarr[i] == 'g' ){
return true;
}
It is easier to work with a String, but unnecessary: you can simply work with the individual characters, uppercasing them to normalize for case:
return arr.length >= 3
&& Character.toUpperCase(arr[0]) == 'A'
&& Character.toUpperCase(arr[1]) == 'T'
&& Character.toUpperCase(arr[2]) == 'G';
This avoids creating any objects, so will likely be faster than converting to String.
You could also just be explicit about the upper and lower case variants:
(arr[0] == 'A' || arr[0] == 'a')
Instead of Character.toUpperCase etc. The downside of that is that it's easy to make a mistake in getting the correct upper/lowercase pairs when you copy and paste (as demonstrated in #Tim's comment below: A/t, rather than A/a).
This would be much easier to handle if you were working with strings instead of character arrays. The reason for this is that using your current approach you will need to check each of the three individual characters, three times, for each starting pattern. That being said, one way to approach this would be to convert the character array back to a string and do the check there:
public boolean isValid(char[] array) {
if (array.length < 3) {
return false;
}
// create string from only first 3 characters of array
String str = new String(array, 0, 3);
return str.equalsIgnoreCase("atg");
}
char[] array = {'A', 't', 'G', 'c', '/', 'C', 'G'}; // ... and more data
isValid(array);
This approach should perform well because it avoids creating a lengthy string from a character array. All we need are the first three characters in order to perform the check.
You can use a String instead of a char array and use indexOf method.
String s = new String(seqarr);
s = s.toLowerCase();
System.out.println(s.indexOf("atg") == 0);
You may use copyValueOf from String to convert the char array to String. Then use equalsIgnoreCase to compare.
public boolean isValid(char[] seqarr) {
return String.copyValueOf(seqarr, 0, 3).equalsIgnoreCase("atg");
}
If I got your question right, then you want to find if the first three characters are either ATG or not, in the right order, like
ATGsomething
aTGsomething
AtGsomething
Atgsomething
...
Then you can do this using regular expressions as well
String str = String.valueOf(seqarr);
if(str.matches("^[Aa][Tt][Gg]")) {
return true;
}
You can also do it by tweaking your code a little bit
if( seqarr.length>=3 && (seqarr[0] == 'A'|| seqarr[0] == 'a') && (seqarr[1] == 'T' ||seqarr[1] == 't') && (seqarr[2] == 'G'|| seqarr[2] == 'g' ){
return true;
I am trying to write a program that evaluates a postfix expression. My idea is to stack the operands and then pop out the necessary operands when an operator occurs. I am trying to check if the input is an operand is an operator or operand, but the only "if" statement of this beginning code is returning "error: illegal start of expression" at the first instance of ||. Am I missing escape characters or something else? Thanks in advance.
public class Evaluate{
char input[] = new char[50];
Stack operands = new Stack();
public string Evaulate(string input){
for (int k = 0; input[k] != null; k++){
char symb = input.charAt[k];
if (symb != (+ || - || * || / || $){
operands.push(symb);
}
}
}
}
For a start, conditions don't quite work that way:
if (symb != (+ || - || * || / || $) ...
What you should be doing is first comparing them with characters rather than "naked" Java tokens (or $).
You should also be doing full comparisons between each || or, since you're using negative logic here to detect non-operators, &&:
if ((symb != '+') && (symb != '-') && ...
There are a few other problems in your code which I haven't mentioned but that should fix your immediate problem.
The expression
symb != (+ || - || * || / || $
is not valid in Java. Even after closing the parentheses and quoting the symbols, like this:
symb != ('+' || '-' || '*' || '/' || '$')
it is still not valid. You may want it to mean something that it does not, based on the way we can use "or" in English (i.e., "symbol is not a plus or a minus or a star or a slash or a dollar sign"). But Java just doesn't do things that way.
Fortunately there is a better way to determine whether a character (in this case symb) is one of a certain set of characters:
if ("+-*/$".indexOf(symb) >= 0) {
This computes the position of symb within the string "+-*/$" which, if symb is one of the desired characters, will be 0, 1, 2, 3, 4, or 5. If it is not, the expression returns -1. So the >=0 check serves as the membership check you are looking for.