Count Even Digits in an Integer in Java [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 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;

Related

there is some sort of error in the syntax of the program "to determine whether the number is prime or not" 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 2 years ago.
Improve this question
Even if I input the number "4", it shows that the number is prime. Please help to find error in the syntax. I have written below the program I coded :
int n = sc.nextInt();
boolean isPrime = true;
for (int i = 2; i < n; i = i + 1)
{if (n % i == 0) {
isPrime = false;
break;}
}
if (isPrime = true)
System.out.println("the number is prime");
else if (isPrime = false)
System.out.println("the number is not prime");
Boolean comparison needs to be done with double equals ==. The way you have it currently, you are setting isPrime to be true in that check. Try this:
if (isPrime == true)
Your program is not complete. You have written assignment statement instead of boolean expression in if statement. '=' sign is for assignment, As 'isPrime' is a boolean variable you can write isPrime in if expression
if(isPrime)
{
System.out.println("the number is prime");
}
else
{
System.out.println("the number is not prime");
}
Use Equality operator == instead of assignment operator = for checking the value of isPrime.
Your code should be:
boolean isPrime = true;
for (int i = 2; i < n; i = i + 1)
{if (n % i == 0) {
isPrime = false;
break;}
}
if (isPrime == true)
System.out.println("the number is prime");
else
System.out.println("the number is not prime");
Also,since if() method's return type is boolean, you can directly check with using ```==````
boolean isPrime = true;
for (int i = 2; i < n; i = i + 1)
{if (n % i == 0) {
isPrime = false;
break;}
}
if (isPrime)
System.out.println("the number is prime");
else
System.out.println("the number is not prime");

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.

Don't know how to write the Javadoc for this short method [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 3 years ago.
Improve this question
I need to write a Javadoc comment for this method:
public static int maxDigit(int n)
{
if (n < 0) return maxDigit(-n);
if (n < 10) return n;
return n % 10 > maxDigit(n / 10) ? n % 10 : maxDigit(n / 10);
}
Basically, it returns the largest digit of a number. For instance, if n=36920 it will return 9. But I don't know how to write the inside's method documentation
i tried to write it but i don't know if it's correct could you help?
if (n < 0)
//in case of n<0 returns -n to the method in order to make the number positive
return maxDigit(-n);
// checks if the number is a digit
if (n < 10)
return n;
//calls the maxDigit method with n - one digit every time , until n<10
int max = maxDigit(n / 10);
// checks if the remainder of n/10 is bigger than max
return (n % 10 > max)? n % 10 : max;
}
/** Find the largest digit in decimal representation of given number.
*#param n The number to search in
*#return The largest digit
*/
public static int maxDigit(int n)
{
if (n < 0) return maxDigit(-n);
if (n < 10) return n;
int max_ = maxDigit(n / 10)
return n % 10 > max_ ? n % 10 : max_;
}
Is this what you meant?
By the way, I optimised the method for you a little. Now it won't cause tree-recursion.

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

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');
}

Prime Number Test always returns true [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 9 years ago.
Improve this question
So I just started some java and I'm trying to get the user to enter a number and test whether it is prime or not. This is the loop I have for the program.
do{
for(testNumber = 2; testNumber < numb; testNumber++){
if(numb % testNumber == 0){
test = false;
}else{
test = true;
}
}
if(test = true){
System.out.println("The number is prime.");
}else{
System.out.println("The number is not prime.");
}
System.out.println("Enter a number. Enter 0 to exit.");
numb = number.nextInt();
}while(numb != 0);
Every number that is entered becomes out to be true! To me the logic seems to be correct.
if(test = true){
should be
if(test == true){
The first one being an "assignment" operator and the second one being a logical (equality test) operator. Read more on the official documentation.
Note
I am not commenting on other parts of your code as a learning exercise for you. Your code can be optimized and improved! You're on the right track. Keep it up!
First, your are using the assignment operator = to compare test to true, which results in test always being true. It's already a boolean, just use it without the extraneous comparison:
if(test){
Second, you are overwriting the value of test in each for loop iteration. Initialize it to true, and only set it to false if you find a factor.
test = true;
for(testNumber = 2; testNumber < numb; testNumber++){
if(numb % testNumber == 0){
test = false;
}
}
Additionally, you don't need to test testNumbers past the square root of the number numb.
int limit = (int) Math.sqrt(numb);
for(testNumber = 2; testNumber <= limit; testNumber++){
You have two problems. First, think about your loop logic: You're actively setting the test variable on every pass through the loop. Since the loop ends at numb - 1, it's nearly always going to set test to true on the last pass. Instead, set test to true before the loop and only set it to false if you find a factor: That will leave it false as soon as you detect it's not prime. (Putting that loop inside a separate method so you can return immediately would be even better.)
isPrime = true;
for(int factor = 2; factor < numb; factor++) { // see below for advice on condition
if(numb % factor == 0)
isPrime = false;
}
Second, you're setting test in your if statement. You must use == to check for equality, and in Java, it's more idiomatic to just use if(test).
As a matter of style, a variable named test is not very descriptive. I suggest the isPrime name I used above.
Finally, you only need to check up to the square root of testNumber, but don't use a floating-point operation and then truncate the result, or you might miss an exact square-root factor.
You should break if you found it and if condition == true
do{
for(testNumber = 2; testNumber < numb; testNumber++){
if(numb % testNumber == 0){
test = false;
break;
}else{
test = true;
}
}
if(test == true){
System.out.println("The number is prime.");
}else{
System.out.println("The number is not prime.");
}
System.out.println("Enter a number. Enter 0 to exit.");
numb = number.nextInt();
}while(numb != 0);

Categories