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.
Related
I have the following code for the solution of Hackerrank.
public static void main(String[] args) {
System.out.println(isBalanced("{(([])[])[]}"));
}
public static String isBalanced(String s) {
Stack<Character> stack = new Stack<>();
stack.push(s.charAt(0));
for (int i = 1; i < s.length(); i++) {
Character c = s.charAt(i);
Character cStack = stack.peek();
if (cStack == '{' && c == '}'
|| cStack == '[' && c == ']'
|| cStack == '(' && c == ')') {
stack.pop();
} else {
stack.push(c);
}
}
if (stack.isEmpty())
return "YES";
return "NO";
}
Although the code seems to working without any problem, it throws the following error on the Hackerrank page. I already test the input in my local IDE as it is {(([])[])[]}, but I am not sure if I need to get the last element (it maybe due to getting it via Character cStack = stack.peek(); and then stack.pop();.
So, could you please have a look at and test this code on Hackerrank page and let me know what is wrong?
Update:
public static String isBalanced(String s) {
Stack<Character> stack = new Stack<>();
stack.push(s.charAt(0));
for (int i = 1; i < s.length(); i++) {
Character c = s.charAt(i);
if (c == '{' || c == '[' || c == '(') {
stack.push(c);
} else if (stack != null) {
Character cStack = stack.peek();
if (cStack == '{' && c == '}'
|| cStack == '[' && c == ']'
|| cStack == '(' && c == ')') {
stack.pop();
}
}
}
if (stack.isEmpty())
return "YES";
return "NO";
}
Before calling stack.peek(), you need to check if the stack is empty or not. Calling pop() or peek() on an empty stack will raise an error.
If the current character is an opening bracket, you don't even need to check the stack top. If it is a closing bracket, then check if the stack is empty or not first. If it is, return false. Otherwise compare the top character and make a decision.
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';
}
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.
When the user enters their ID I want it to be in a specific format, they are mostly explained within the comments. I was wondering if their was an easier more efficient way of doing this. Also whether or not there is a way to change the entered letters to capital the way I've done the code, or any other method.
private boolean setCustomerID(String id) {
//Validates the customerID contains 3 letters a hypthen then 4 numbers
if ((id.charAt(0) < 'A' || id.charAt(0) > 'Z')
|| (id.charAt(1) < 'A' || id.charAt(1) > 'Z')
|| (id.charAt(2) < 'A' || id.charAt(2) > 'Z')
|| (id.charAt(3) != '-')
|| !isDigit(id.charAt(4))
|| !isDigit(id.charAt(5))
|| !isDigit(id.charAt(6))
|| !isDigit(id.charAt(7))) {
return false;
//Checks the user enters P, B or C for first letter
} else if ((id.charAt(0) == 'P' || id.charAt(0) == 'B' || id.charAt(0) == 'E')
//Checks the second and third letter are in the correct region
&& ((id.charAt(1) == 'S' && id.charAt(2) == 'C')
|| (id.charAt(1) == 'S' && id.charAt(2) == 'C')
|| (id.charAt(1) == 'W' && id.charAt(2) == 'A')
|| (id.charAt(1) == 'N' && id.charAt(2) == 'I')
|| (id.charAt(1) == 'N' && id.charAt(2) == 'E')
|| (id.charAt(1) == 'N' && id.charAt(2) == 'W')
|| (id.charAt(1) == 'M' && id.charAt(2) == 'I')
|| (id.charAt(1) == 'E' && id.charAt(2) == 'A')
|| (id.charAt(1) == 'S' && id.charAt(2) == 'E')
|| (id.charAt(1) == 'S' && id.charAt(2) == 'W'))){
// SC (Scotland), WA (Wales), NI (Northern Ireland), NE (North-East), NW (North-West),
//MI (Midlands), EA (East Anglia), SE (South-East), SW (South-West).
return true;
}
return false;
}
Use regex.
private boolean matchCustomerID(String id) {
return id.matches("^[PBE](?:SC|WA|NI|NE|NW|MI|EA|SE|SW)-\\d{4}\\b");
}
Regular expressions are one way of solving the problem. You can compose the pattern in a way that makes maintenance easier. Building on rcorreia's pattern, you can do something like:
private boolean setCustomerID(String id) {
char[] validFirstLetters = { 'P', 'B', 'E' };
String[] validRegions = { "SC", "WA", "NI", "NE", "NW", "MI", "EA", "SE", "SW" };
String pattern =
String.format("^[%s](?:%s)-\\d{4}$", new String(validFirstLetters),
String.join("|", validRegions));
return id.matches(pattern);
}
Note that this uses String.join() from Java 8. If you don't use Java 8 yet, consider using StringUtils from Apache Commons Lang.
Regexp is a great feature, but not easy to write and understand..
In this case, I would follow your way, but I would define some testing method. In this manner the code will be readable and easy to write Unit tests for it.
If you need some change later, you will understand the code.
Example:
testForLength();
testForLetters();
testForFirstTwoLetters();
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.