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.
Related
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';
}
public static boolean isValidReferenceCode(String rc) {
boolean validCode = true;
if (rc.length() != 6 ) {
validCode = false;
} else if ( !Character.isLetter(rc.charAt(0)) ||
!Character.isLetter(rc.charAt(1)) ||
!Character.isDigit(rc.charAt(2)) ||
!Character.isDigit(rc.charAt(3)) ||
!Character.isDigit(rc.charAt(4)) ||
!Character.isLetter(rc.charAt(5))) {
validCode = false;
} else if ( (!rc.substring(5).matches("B")) || (!rc.substring(5).matches("N")) ) {
validCode = false;
}
return validCode;
}
This is my validation method inside a big program, I need a validation that requires the user to input at least 6 characters, first two being letters, next three being digits, and the last character either a "B" or "N" right now it's not doing that. After some trial and error, the first two IF statements seem to be correct and work when I delete the 3rd if statement about substrings, am I using the correct Syntax here? Would really appreciate help!
Find below logic , it will work . Better to use regular expressions .
public static boolean isValidReferenceCode(String rc) {
boolean validCode = true;
String pattern= "^[a-zA-Z]{2}[0-9]{3}[BN]}$";
if (rc.length() != 6) {
validCode = false;
}
validCode = rc.matches(pattern);
return validCode;
}
Another way to solve it is to use the original code with:
} else if ( (rc.charAt(5) != 'B') && (rc.charAt(5) != 'N') ) {
You need both to be misses (i.e., use an && instead of an ||).
Instead of a cascade of ifs and negative logic, you can do the entire test more clearly in a single positive-logic expression:
public static boolean isValidReferenceCode(String rc) {
return
rc.length() == 6 &&
Character.isLetter(rc.charAt(0)) &&
Character.isLetter(rc.charAt(1)) &&
Character.isDigit(rc.charAt(2)) &&
Character.isDigit(rc.charAt(3)) &&
Character.isDigit(rc.charAt(4)) &&
(rc.charAt(5) == 'B' || rc.charAt(5) == 'N');
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 am writing a function to fulfill these requirements:
Given a string, return true if it is a nesting of zero or more pairs of parenthesis, like (()) or ((())). Suggestion: check the first and last chars, and then recur on what's inside them.
nestParen("(())") → true
nestParen("((()))") → true
nestParen("(((x))") → false
The correct solution shown on the site is:
public boolean nestParen(String str) {
if (str.equals("")) return true;
if (str.charAt(0) == '(' && str.charAt(str.length()-1) == ')')
return nestParen(str.substring(1,str.length()-1));
else
return false;
}
I don't understand why this works. If the given string has a character other than ( like a ", won't it hit the else case and return false rather than skipping to the next (?
This will definitely not work if the input string contain some thing other than ( and ) to make this work just call another function like below before calling this function:
clean(String str){
String str = "(((X+y)+z))";
String retStr = "";
for(int i = 0 ; i<str.length() ; i++){
if(str.charAt(i) == '(' || str.charAt(i) == ')')
{
retStr += str.charAt(i);
}
}
return retStr
}
and then call your recursive function with input of retStr.
As seems typical with much example code, the suggested correct solution is inadiquate.
Here is an actually correct solution:
public boolean nestParen(final String value)
{
if (value != null)
{
if (value.isEmpty())
{
return true;
}
if (value.charAt(0) == '(' && value.charAt(value.length()-1) == ')')
{
return nestParen(value.substring(1, value.length()-1));
}
else
{
return false;
}
}
else // value is null
{
return true;
}
}
Explanation: (same as with the other answer)
if the parameter is not null, continue. This prevents NullPointerExceptions.
if the parameter is empty, return true. The problem appears to be return true if a string contains zero or more nested pairs of parens and nothing else.
If the first char is '(' and the last char is ')', strip these chars and check again (this is the recursion).
otherwise (first is not '(' and/or last is not ')') return false.
lastly, if the parameter was null, return true (it contains zero pairs and nothing else).
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.