I made this method in java that replaces the vowels of a String if it contains letter 'i':
public static boolean esVocal(Character c) {
boolean res = false;
if (c == 'a' | c == 'o' | c == 'e' | c == 'u') {
res = true;
}
}
Anyway, the error that gives me is:
illegal start of expression
And at the end, it says that the method requires a return.
Could the error be in the syntax?
Explanation
Your method signature
public static boolean esVocal(Character c)
declares the return type boolean. This means your method is supposed to return something of type boolean.
Solution
If you don't want to return anything you should declare the return type as void:
public static void esVocal(Character c)
Or if you want to return something you need to add the corresponding statement to your method:
public static boolean esVocal(Character c) {
boolean res = false;
if (c == 'a' | c == 'o' | c == 'e' | c == 'u') {
res = true;
}
// You probably wanted to return this
return res;
}
Notes
Note that you can reduce your method by directly returning the resulting boolean like:
public static boolean esVocal(Character c) {
return c == 'a' | c == 'o' | c == 'e' | c == 'u';
}
The operator | on numbers is not the logical or. It is a bit-wise inclusive or operation which makes some bit-manipulations on values like:
0100 1110
or 1000 1011
---------
1100 1111
However on boolean expressions, like in your case, it also performs as logical or (see JLS 15.22.2).
There is also the operator || which always behaves as logical or.
Note that there is a difference between both operators, even when using on boolean values. The | operator will always compute the whole expression, even when the resulting value already is clear. The || aborts evaluation if the result already is clear like in
true || someBoolean || someOtherBoolean
The true already makes the whole result true and || will thus not evaluate the rest of the expression whereas | will.
In your case however you probably want to use ||:
c == 'a' || c == 'o' || c == 'e' || c == 'u'
For the logical and &, && the difference is the same.
If you are considering logical OR operations, it is preferred to use || instead of | operator. So, you can update the if condition as follows. [A nice explanation is provided in the other answer]
if (c=='a' || c=='o' || c=='e' || c=='u'){
res=true;
}
Also, your method signature declares the return type as boolean, so you are required to return a boolean value from the function. You can simply do the following.
public static boolean esVocal(Character c){
return c=='a' || c=='o' || c=='e' || c=='u';
}
Related
When I tried to run the code below, an error appeared:
error: illegal start of expression
What does this error mean? How will I be able to fix it?
public boolean isVowel(char c) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||) {
return true;
}
return false;
}
There's a trailing or (||), remove it.
I'm trying to write a code that determines whether two inputs of DNA sequences are reverse compliments or not. The program asks the user to provide the sequences as a string.
I have the code executing properly but I want to write a single if statement that continues the program if the characters are all 'A' 'T' 'C' or 'G'.
This is what i came up with on my own, but it doesnt work, and it doesn't even look close. I'm new to the language and come from ADA and am just stumped any help would be great.
if ( seqFirst.charAt(i) != 'A' || seqFirst.charAt(i) != 'T' ||
seqFirst.charAt(i) != 'C' || seqFirst.charAt(i) != 'G' ||
seqSecond.charAt(i) != 'A' || seqSecond.charAt(i) != 'T' ||
seqSecond.charAt(i) != 'C' || seqSecond.charAt(i) != 'G' )
You simply need to change || to && throughout the conditional expression.
By way of an explanation, consider this simplified version of your code:
if (c != 'A' || c != 'T' ) { // IS BAD }
and consider the case where c is 'A'. The first predicate evaluates to false. The second predicate evaluates to true. The entire expression is false || true ... which is true ... "BAD"
Now change the || to && and you get false && true ... which is false ... "NOT BAD"
I'm new to the language and come from ADA ...
That's not the real problem. The problem is understanding how boolean algebra works; i.e. DeMorgan's Laws.
As i know, 2 DNA string are reverse compliments when one of these equals to another, but reversed and with changed nucleotides. Since i dont know your version of Java, i wrote some readable method in Java7:
public static boolean isComplimentaryReverse(String str1, String str2) {
//invalid input, could throw exception
if (str1.length() != str2.length()) {
return false;
}
//could be static final field
Map<Character, Character> replaceTable = new HashMap<>();
replaceTable.put('G', 'C');
replaceTable.put('C', 'G');
replaceTable.put('T', 'A');
replaceTable.put('A', 'T');
String reverseStr1 = new StringBuilder(str1).reverse().toString();
for (int i = 0; i < str2.length(); i++) {
//invalid input, could throw exception
if (!replaceTable.containsKey(reverseStr1.charAt(i))) {
return false;
}
if (str2.charAt(i) != replaceTable.get(reverseStr1.charAt(i))) {
return false;
}
}
return true;
}
Simplify with a regular expression.
private static final String VALID_DNA = "[ATCG]+";
...
if (seqFirst.matches(VALID_DNA) && seqSecond.matches(VALID_DNA)) {
// keep going...
}
I'm seeing a possible De Morgan's Law issue. Remember !(a or b) = !a and !b.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
Given a string personName, I'm trying to create a boolean condition2 equal to the condition
the first or last letter in personName is 'A' (case-insensitive). e.g., 'aha' or 'A'
Here's what I've tried so far:
boolean condition2;
if (personName.charAt(0) = "a" || personName.charAt(personName.length()-1) = "a") {
condition2 = true;
} else {
condition2 = false;
}
char type in Java is a character so wouldn't you be looking for something like this?
boolean condition2;
if((personName.charAt(0) == 'a' || personName.charAt(0) == 'A') &&
(personName.charAt(personName.length()-1) == 'a' || personName.charAt(personName.length()-1) == 'A'))
{
condition2 = true;
}
else{
condition2 = false;
}
For your first question where first and last character of a String should be 'a'
boolean condition1 = false;
if(personName.charAt(0) == 'a' && personName.charAt(personName.length()-1) == 'a') {
condition1 = true;
}
For your second condition where variable should be true only if age is in the range [18,24]
boolean condition2 = false;
if(personAge >=18 && personAge <=24) {
condition2 = true;
}
You can do it this way except comparison operator is == and you compare characters, not String.
So right way would be:
Character.toLowerCase(personName.charAt(0)) == 'a'
See, double equals and single quote.
use single quote for data type char. and convert it to lower case, so that it allow whether it's upper case or lower case.
Also use == when comparing if it's equal. this = sign, is for assigning value
if(Character.toLowerCase(personName.charAt(0)) == 'a' ||
Character.toLowerCase(personName.charAt(personName.length()-1)) == 'a')
it will look like this
boolean condition2;
if(Character.toLowerCase(personName.charAt(0)) == 'a' || Character.toLowerCase(personName.charAt(personName.length()-1)) == 'a')
{
condition2 = true;
}
else{
condition2 = false;
}
Your problem can be solve in this manner;
public static void main(String[] args) {
String s = "bsdadasd";
boolean condition2;
System.out.println(check(s.toLowerCase().charAt(0),s.toLowerCase().charAt(s.length()-1)));
}
public static boolean check(char a,char b){
return (a == 'a' || b == 'a');
}
You can pass the two characters as parameters for a method where it return true or falsedepending on the condition.
Since both characters are irrelevant of its case first made them to lowercase. toLowerCase() then passed the char at 0 and char at last.
The return statement will return the true or false to you.
And also use == to check if similar = means assigning.
It is circuitous to write
boolean b;
if (some boolean expression)
b = true;
else
b = false;
Much simpler to write
boolean b = some boolean expression;
For reasons I don't understand, there is a widespread reluctance to write a boolean expression (as distinct from the simple literal values true/false) outside an 'if' statement.
And don't get me started on if (b == true)
I actually try to convert four different Boolean into true/false.
My case is,
True false false false Then true else false
false True false false Then true else false
false false True false Then true else false
false false false True Then true else false
I tried like this,
int a=1;
int b=0;
int c=0;
int d=0;
int cnt=0;
// A block of code will be executed only when any one of the four variables is 1 and
//the rest of them is 0. and another block will be executed when the above mentioned
//condition become false.
if (a==0) { cnt+=1; }
if (b==0) { cnt+=1; }
if (c==0) { cnt+=1; }
if (d==0) { cnt+=1; }
if (cnt==3) { // true block } else { //false block }
The above code is working perfectly fine, But i had taken a challenge to check this condition in a single if statement. Then i tried like this.
if(!((!(a==0) && !(b==0)) && (!(c==0) && !(d==0))))
{
//true block
}
else
{
//false block
}
The above condition is failing in some combinations(a=1 b=0 c=1 d=1). Can anybody point out what the issue is.? or suggest any new ideas.?
My objective is convert (3 false + 1 true) into true other wise into false.
[Note: I just gave the scenario for understanding purpose only. a,b,c,d value may be differ. See my objective. Don't say answers in favor of 1 and 0]
I think I would use the following method, which makes the algorithm reusable and support any number of arguments. It returns true only if exactly one argument was true.
private boolean oneTrue(boolean... args){
boolean found = false;
for (boolean arg : args) {
if(found && arg){
return false;
}
found |= arg;
}
return found;
}
You can test it like this:
private void test(){
boolean a = false;
boolean b = true;
boolean c = false;
boolean d = false;
System.out.println(oneTrue(a,b,c,d));
}
Shortest pure bool solution which I can suggest:
System.out.println((a | b) ^ (c | d)) & ((a ^ b) | (c ^ d));
But in your program already already used 1 and 0, if it variables always 1 and 0, you may not use boolean just use following:
if (a + b + c + d == 1)
{
// true
} else
{
// false
}
if this varibales may have any values. In this case I recommend convert it to 1 and 0 instead of boolean and again can simply calculate sum.
How about this?
boolean a = true;
boolean b = false;
boolean c = false;
boolean d = false;
if ((a ? 1 : 0) + (b ? 1 : 0) + (c ? 1 : 0) + (d ? 1 : 0) == 1) {
System.out.println("You win!");
}
[edit]... or here's another way to do it :
if ((a ^ b ^ c ^ d) & ((a & b) == (c & d))) {
System.out.println("**XOR** You win!");
}
You can use the following expression:
a && !(b || c || d) ||
b && !(a || c || d) ||
c && !(a || b || d) ||
d && !(a || b || c)
I'm just learning java, and I have an assignment where I have to write a program that checks the validity of expressions about sets. Valid expressions are capital letters, an expression with a tilde in front, and can be combined using + and x as well as with parentheses. I've written a program that almost works, but I can't figure out how to get the binary operators to work with the parentheses.
It may also be that I have approached the problem in the wrong way (trying to validate from left to right, ignoring everything to the left once it's been validated). I can use any help I can get about writing recursive programs for this sort of problem; that is, if you have any pointers for a better way of approaching the problem, that would be incredibly helpful.
For reference, here is the code that I have:
public static boolean check(String expr) {
char spot;
int close=0;
expr = expr.trim();
//base case
if (expr.length() == 1 && expr.charAt(0)>= 'A' && expr.charAt(0) <= 'Z')
return true;
if (expr.charAt(0) == '~') {
if (expr.charAt(1) == 'x' || expr.charAt(1) == '+' || expr.charAt(1) == ')')
return false;
return check(expr.substring(1));
}
if (expr.indexOf('x') > 0 && expr.indexOf('x') > expr.indexOf(')')) {
int x = expr.indexOf('x');
if (check(expr.substring(0, x)) && check(expr.substring(x)))
return true;
}
if (expr.indexOf('+') > 0 && expr.indexOf('+') > expr.indexOf(')')) {
int plus = expr.indexOf('+');
if (check(expr.substring(0, plus)) && check(expr.substring(plus+1)))
return true;
}
if (expr.charAt(0) == '(') {
close = findEnd(expr.substring(1));
if (close < 0)
return false;
if (check(expr.substring(1,close)) && check(expr.substring(close+1)))
return true;
}
return false;
}
I'm not sure why your code is that complex. Recursion for this is pretty simple overall; here's what I'd do:
public static boolean check(String str) {
if(str.equals("")) return true;
if(str.charAt(0).isAlphaNumeric() || str.charAt(0) == '(' || str.charAt(0) == ')') return check(str.substring(1));
return false;
}
Your edge cases are if the string is empty; if this is the case, then the string is valid. If the character doesn't match what you're looking for, return false. Otherwise, check the next character.