Java's weird unreachable code error [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm writing a program that identifies whether a String "xyz" is certralized in the input String or not. I create a variable that stores the position of "xyz" with a for loop, and then compare it to the number of chars before and after, creating ints with .substring() and .length(). Strangely enough, the code doesn't compile after the first if - which returns true or false, saying whatever return statement after that is unreachable.
Could anyone help me wrap my head around this?
Thanks a lot!
Maybe because the length variables haven't been run yet and, for the compiler,
they will always be different? How to solve that?
public static boolean xyzCenter(String str){
//identifies the position of "xyz" within the String.
int xyzPosition=1;
//loops through the string to save the position of the fragment in a variable.
for(int i = 0; i<str.length(); ++i){
if(str.length()>i+2 && str.substring(i, i+3).equals("xyz")){
xyzPosition=i;
}
}
//ints that determine the length of what comes before "xyz", and the
length of what comes after.
int lengthBeg = str.substring(0, xyzPosition).length();
int lengthEnd = str.substring(xyzPosition+3, str.length()).length();
if ((lengthBeg != lengthEnd));{
return false;
} //this compiles.
return true; //this doesn't!

if ((lengthBeg != lengthEnd)); <----- remove that semicolon
When you put a semicolon at the end of an if it is like having an empty if block. Your code is equivalent to
if ((lengthBeg != lengthEnd)) {
// Do nothing
}
{
return false;
}
return true; // Unreachable because we already returned false

Related

Java error when I try to create an object with a constructor with a string parameter [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I created two constructors in my Move class, one with two int parameter and one with String parameter:
public Move(int row,int col)
{
int[] [] Move = new int[row][col];
}
public Move(String r)
{
String move = new String(r);
}
Then I try making an object:
Move m = new Move(1,1);
m = new Move("E1");
//The second one does not work and I get this as an error in java:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47)
at java.base/java.lang.String.charAt(String.java:693)
at Move.<init>(Move.java:16)
at moveTester.main(moveTester.java:10)
how do I fix it, thank you!
You already have a String parameter, you can use it as it is, you do not need to create a new one, see:
public Move(String r)
{
String move = r;
}
However, move will only be a local variable, you probably want something different, but that's another step, which you will need to do after this one.

java regex questions [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Given that I have a string of number, like "12354789556", I need to check that string whether has digits from 0 to 9 at least once.
Can anyone tell me whether i can express this in regex please?
If your strings contains only digits for example "123548955664789556" then try:
System.out.println(myString.chars().distinct().count() == 10);
if your string can also contain letters for example sth like "bbb1235489556fhjerfs64789556"
System.out.println(myString.replaceAll("[^\\d]", "").chars().distinct().count() == 10);
With lookaheads :
^(?=.*0)(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5)(?=.*6)(?=.*7)(?=.*8)(?=.*9)
If you want to restrict the string to digits only in addition to making sure it contains every digit :
^(?=.*0)(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5)(?=.*6)(?=.*7)(?=.*8)(?=.*9)\d+$
Note that a version without lookaheads would be technically possible, but would realistically have to be crafted by code as it would have to enumerate all possible orders between digits (10! = 3628800 enumerations).
You can also do it in Java like this:
boolean containsAll = true;
for (int i = 0; i < 10; i++) {
if (!str.contains("" + i)) {
containsAll = false;
}
}
return containsAll;
A non-regex way would be to loop through the String and return false if the indexOf returns -1:
static boolean checkAll(String s, char[] allNums) {
for (int i = 0; i < allNums.length; i++) {
if (s.indexOf(allNums[i]) == -1) {
return false;
}
}
return true;
}
Example

The output of this loop should be less than 1, but I get very large numbers [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
This program is supposed to count the number of characters "c" and "g" in genes in the DNA string and then take that number and divide it by the length of each gene. The number of cs and gs is always < gene.length(), therefore the output should be something like 0.65555, 0.35657 etc, but I get large numbers like 141, etc. Not sure what is wrong with this loop.
public void testfile(){
String dnaTest = "aaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaacccttaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctcacccttctaact";
int counter = 0;
for(String gene : s1.data()) {
for (char cORg : gene.toCharArray()) {
if ((cORg == 'c') || (cORg == 'g')) {
counter ++;
}
System.out.print(gene +" ");
}
float cgRatioGenes = counter/gene.length();
System.out.println("cgRatio: " + cgRatioGenes);
}
}
}
If you spot the error, let me know. Thanks!
EDIT
Even without the parentesis at the end of the DNA string and with the closing bracket, the loop was not producing the results I expected. Therefore, it is not off topic.
Two problems:
First, you never reinitialize counter when you start the loop again. Move that declaration inside the loop so that each repetition starts with a counter of zero.
If you make that change, all your results will be zero though, because you're diving two integers, which will truncate the results. Cast one to float, so that it keeps the decimal part. See this question for more information on the problem
for(String gene : s1.data()) {
int counter = 0; //Moved inside the for loop, so that it always starts at 0
for (char cORg : gene.toCharArray()) {
if ((cORg == 'c') || (cORg == 'g')) {
counter ++;
}
System.out.print(gene +" ");
}
//Floating point division, instead of integer division
float cgRatioGenes = ((float)counter)/gene.length();
System.out.println("cgRatio: " + cgRatioGenes);
}
One potential problem is here
float cgRatioGenes = counter/gene.length();
As gene.length() is an integer value the ratio is not computed correctly. Instead, you should cast one of them to float like this
float cgRatioGenes = ((float)counter)/gene.length();
In addition, the counter variable should probably be initialized to zero for each gene (unless you want to count the c/g values over all genes).
This probably does not explain the behavior you are observing, but it is not possible to figure it out unless a complete working example is given.
It's a little unclear what the exact intent of this code is, but my guess is that you're using one int counter for every gene in s1.data(). I assume you want to count the number of valid characters per gene, not in the entire pool.
If you do want to count for the entire pool, the problem is that you're peforming gene.length outside of the for, which should honestly throw a compiler error unless you have a gene defined somewhere else as well.
Additionally, you're dividing two ints for your answer, which will yield an int. Case one of your variables to float to get a decimal answer.

How does this return the correct output? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
public int scoreUp(String[] key, String[] answers) {
int score = 0;
for (int i = 0; i < key.length; i++) {
if (key[i] == answers[i])
score += 4;
else if (answers[i] != "?" && answers[i] != key[i])
score--;
}
return score;
}
This works on http://codingbat.com/prob/p180365 but it uses == to compare Strings instead of the equals method? How come?
How does this return the correct output?
If both the key array and the answer array uses interned strings, then == is valid for comparison.
It is a dangerous assumption to make, so programmers should always use equals() for comparing strings, even if interned is guaranteed, because such guarantee may disappear in the future, and the the subtle implicit assumption may be overlooked. Always using equals() is futureproofing the code.
if (key[i] == answers[i]) in a valid reference comparing between 2 strings,
there is no reason for the compiler to complain, in fact that can be a logically way to check if objects are the same.
if that is the right way to compare string is another question.

Scope of Local Variable [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm still confused with scope of local variable
This code doesn't work because i in "i & n" is not resolved. I have identified it on for loops as int i =0. is it not enough? (This is adding nth character altogether our of string).
public String everyNth(String str, int n) {
String result = "";
for (int i = 0; i <= str.length(); i++); {
if (i%n == 0) {
result = result + str.charAt(i);
}
else {
result = result;
}
}
return result;
}
To expand on Jon Skeet's answer-worthy comment, the semi-colon at the end of for (int i = 0; i <= str.length(); i++); finishes the for-statement, and i is no longer in scope after the semi-colon.
You are a few errors:
You can remove the else{ ... } part because you don't need it.
You have a extra ';' in your for loop statement.
There is a mistake on the index of the for loop. You need to do 'i less than' str.length(), instead of i<=str.length(). Basically your for loop will try to access the full-length index of your character array, but actually it exceeds length. For example, the index for string 'hello' is 0,1,2,3,4. But "hello".length() is actually 5. If you try to access the 5th index of your string, you will see a 'java.lang.StringIndexOutOfBoundsException' exception.
Also, you want the every Nth value, you want to do (i-1)%n. Again it is because of the index issue. Try to plug in parameters in your logic and use your pencil to write down the result, and you will see why.
And of course when i==0, you don't want (0-1)%n to happen. So skip i==0 by adding 'i!=0'.
Now, the following is the working code:
public static String everyNth(String str, int n) {
String result = "";
for (int i = 0; i < str.length(); i++) {
if ((i-1)%n == 0 && i!=0)
result = result + str.charAt(i);
}
return result;
}

Categories