Which one of these solutions has a better style/performance? [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I found an interesting exercise on codingBat and now I have a Question About the Solution. The Task was:
Given a string, return true if the first instance of x in the string is immediately followed by another x.
What I wrote is:
boolean doubleX(String str) {
return str.contains("x") ? str.indexOf('x') == str.length() - 1 ? false : str.charAt(str.indexOf('x')) == str.charAt(str.indexOf('x') + 1) : false;
}
The solution they had on their page was:
boolean doubleX(String str) {
int i = str.indexOf("x");
if (i == -1) return false; // no "x" at all
// Is char at i+1 also an "x"?
if (i+1 >= str.length()) return false; // check i+1 in bounds?
return str.substring(i+1, i+2).equals("x");
So now my Question is which solution has the better coding style? Which solution is more Beautiful or even more efficient?
Thanks for all answers

I would probably code it like this:
boolean doubleX(String str)
{
int index = str.indexOf("x");
return (index >= 0 && index == str.indexOf("xx", index));
}
Probably not the most performant, but it handles every possibility.
It can be slow if indexOf("x") and indexOf("xx") are far apart (unnecessary, long search for "xx") or if both indices are very high (long search done twice).
So another, slightly less intuitive, but more performant solution could be:
boolean doubleX(String str)
{
int index = str.indexOf("x");
return (index >= 0 && index < str.length() - 1 && str.charAt(index + 1) == 'x');
}

Related

while (1) loop with continue and break statements [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I need help with a while(1) loop that contains a continue and break statement. It must count from numbers 1 to 20 and for every even number, it must output the values. I have to use a continue after my writeToPage statement and use a break statement when it reaches 20.
This is what I tested out but the file will not even load:
writeToPage("Program 4: Continue and Break");
writeToPage("");
while(1) {
if (i % 2 == 0){
writeToPage(+ i);
continue;
}
if (i >= 20){
break;
}
}
I'm not sure if I'm putting them in the wrong place.
For infinite loop, you need to write while(true) instead of while(1).
If i % 2 != 0 is true, simply increment i by 1 and continue; otherwise, print the value of i and increment i by 1.
Demo:
public class Main {
public static void main(String[] args) {
int i = 1;
while (true) {
if (i % 2 != 0) {
i++;
continue;
} else {
writeToPage(i);
i++;
}
if (i >= 20) {
break;
}
}
}
static void writeToPage(int i) {
System.out.println(i);
}
}
Output:
2
4
6
8
10
12
14
16
18
20

What's causing this Stack Overflow error when there is no infinite recursive method? [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 2 years ago.
Improve this question
I am making a chess program in Java. I have a boolean method that takes the location that the user would like to move a rook to, in the form of two ints, and based on the rook's current row and column, determines if the rook can move there, using for loops. Here is one of the loops as an example.
int nc = col - 1;
while (nc >= 0){
moves.add(new Integer[]{row, nc});
if (locals[row][nc] != null)
break;
nc--;
}
moves is an ArrayList that I have declared earlier in the program. It stores a list of all the valid moves, and this is one of the for loops I use to instantiate it.
The issue is, each time I run this code, the lines that include the add methods are highlighted for being infinite loops, and the code will not run. What am I doing wrong?
Edit:
This is the exact error message that the software is showing me:
Additionally, I'm going to post the full text of the method. I'm not sure if any of it is relevant to my question, but it might prove helpful.
public boolean isValidMove(int r, int c){
Piece[][] locals = Chess.getBoard();
if (r < 0 || c < 0 || r > 7 || c > 7 || (locals[r][c] != null && locals[r][c].getWhite() == isWhite))
return false;
ArrayList<Integer[]> moves = new ArrayList<Integer[]>();
int nc = col - 1;
while (nc >= 0){
moves.add(new Integer[]{row, nc});
if (locals[row][nc] != null)
break;
nc--;
}
nc = col + 1;
while (nc < 8){
moves.add(new Integer[]{row, nc});
if (locals[row][nc] != null)
break;
nc++;
}
int nr = row - 1;
while (nr >= 0){
moves.add(new Integer[]{nr, col});
if (locals[nr][col] != null)
break;
nr--;
}
nr = row + 1;
while (nr < 8){
moves.add(new Integer[]{nr, col});
if (locals[nr][col] != null)
break;
nr++;
}
for (Integer[] ints : moves){
if (ints[0] == r && ints[1] == c)
return true;
}
return false;
}
I discovered what is wrong the program and managed to fix it. The loop in question does not in fact iterate forever, however a method somewhere in this program called another method which in turn called the original method. Hence, the Stack Overflow error without any one infinitely recursive method.

What is my mistake in this problem. Simple Comparison Error [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 3 years ago.
Improve this question
Task
Given an integer, n, perform the following conditional actions:
If n is odd, print Weird
If n is even and in the inclusive range of 2 to 5 , print Not Weird
If n is even and in the inclusive range of 6 to 20, print Weird
If n is even and greater than 20, print Not Weird
I have written a code but it is showing error in printing 18 and 20.
public static void main(String[] args) {
int N = scanner.nextInt();
scanner.close();
if(N%2 != 0){
System.out.println("Weird");
}
else if(N%2 ==0 && N>=2||N<=5)
{
System.out.println("Not Weird");
}
else if(N%2 ==0 && N>=6||N<=20)
{
System.out.println("Weird");
}
else if(N%2 ==0 && N>20)
{
System.out.println("Not Weird");
}
}
}
You need to change your or condition || to and condition && to check for the range like
else if(N%2 == 0 && N >= 2 && N <= 5)

Count Even Digits in an Integer in Java [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 5 years ago.
Improve this question
I am trying to write a method in Java that will return true if an integer only consists of even digits.
For example when the input integer is 2468, the method will return true.
Another example, if the input integer is -68, the method will return true. If the integer consisted of 24638, the method should return false.
I also am trying to use only integers. I do not want to use ToString() to take the length of the integer as my condition in my loop and I also do not want to use an array.
I have searched the forums but most replies seem to use ToString() or arrays of which I’m avoiding.
My code is below:
int countEven = 0;
int countOdd = 0;
if (n == 0)
countEven++;
while (n != 0) {
int lastdigit = n % 10;
if (lastdigit == 0 || lastdigit % 2 == 0)
countEven++;
else
countOdd++;
n = n /10;
}
if (countEven >= 0); return true;
You are not checking the condition for countodd. Lets say number is 235. Your counteven will be 1 and countodd will be 2. Then your last if condition will return true no matter what. Instead try this,
while(n != 0){
int lastdigit = n % 10;
if(lastdigit % 2 == 1)
return false;
n = n /10;
}
return true;
The problem is that your last if statement is not correct.
Try this:
if (countOdd > 0)
return false;
else
return true;

OR with 3 arguments in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Why does this statement does not work
boolean b = (y==3-x)||(y==3)||(y=3+x);
but this one does
boolean b = (y==3-x)||(y==3);
b = b || (y == x-3);
and && statement has no problems with number of arguments passed
boolean b = x < 7 && x >= 0 && y < 7 && y >= 0;
Because in the first case:
boolean b = (y==3-x)||(y==3)||(y=3+x);
You are doing the assignment not comparison for (y=3+x)
Change it to:
boolean b = (y==3-x)||(y==3)||(y==3+x);
and it will work for you
However in the second case:
boolean b = (y==3-x)||(y==3);
b = b || (y == x-3);
You are doing the comparison everywhere thats why it is working for you!
Also in the third case you are doing comparison
boolean b = x < 7 && x >= 0 && y < 7 && y >= 0;
NOTE:-
== is for comparison and = is for assigment.
<,>,<=,>=, == are all used for comparison
You missed an equals sign, meaning the last parenthesis assigns 3+xto b, evaluates to int rather than boolean and so can't be used for a logical OR expression. This works, though:
boolean b = (y==3-x)||(y==3)||(y==3+x);

Categories