I'm having a problem with my Java code. Specifically, one of my if statements containing an && is not returning True for certain inputs like I expect it to.
The snippet in question:
if (num%2==1 && num < 0) { //why is not reading this statement?
negodd ++;
}
Sample inputs and outputs vs expected outputs:
Enter any number to continue. Enter 0 to stop :
1
2
-2
-1
0 // not counted as a number since it is a stop function.
Output of my code. What it should be.
You Entered 4 numbers : You Entered 4 numbers :
1 negative even 1 negative even
1 positive even 1 positive even
0 negative odd 1 negative odd <--should read the 1
1 positive odd 1 positive odd
The full code in case that helps:
import java.util.Scanner;
public class stupid {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
int num = 0;
int negodd = 0, count = 0, posseven = 0;
int possodd = 0; int negeven=0;
System.out.println("Enter any number to continue. Enter 0 to stop : ");
num = x.nextInt();
if(num==0){
System.out.print("You immediately stop");
System.exit(0);
}
while (num != 0) {
count ++;
if (num%2==1 && num > 0) {
possodd ++;
}
if (num%2==1 && num < 0) { //why is not reading this statement?
negodd ++;
}
if (num%2==0 && num > 0) {
posseven ++;
}
if (num%2==0 && num < 0) {
negeven++;
}
num = x.nextInt();
}
System.out.printf("You Entered %d numbers\n",count);
System.out.printf("%d negative even \n",negeven);
System.out.printf("%d positive even\n",posseven);
System.out.printf("%d negative odd\n",negodd);
System.out.printf("%d positive odd\n",possodd);
}
}
Thanks in advance!
Using the modulo operator with negative numbers gives you a different result than you might think.
1 % 2 == 1
2 % 2 == 0
-2 % 2 == 0
-1 % 2 == -1
To get the result you want, you can replace your modulo tests with num % 2 == 0 and num % 2 != 0.
1 % 2 == 1
2 % 2 == 0
-2 % 2 == 0
-1 % 2 == -1
Here, -1%2 does not results in 1. Hence, it will not increment value of negodd variable.
In JAVA, negative number modulo will give same result as positive number modulo but with a negative sign. 0 is neutral thus it will not have any sign.
-1 % 2 is going to return -1, not 1, where -2 % 2 will give a result of 0.
Related
how do I get this loop to print all the divisors with two user inputted numbers including 1 but just print 1 and relatively prime when the two numbers have no common divisors.
System.out.println("Common divisors of " + a + " and " + b + ":");
for (int i = 1; i <= b; i++)
if (a % i == 0 && b % i == 0) {
if (a % i == 0 && b % i == 0) {
System.out.println(i);
if (i == 1)
System.out.println("Relatively Prime");
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter two positive integers:");
int input1 = scan.nextInt();
int input2 = scan.nextInt();
printCommonDivisors(input1, input2);
}
}
Right now it says relatively prime after 1 even if the numbers have common divisors.
I am just trying to get it to say relatively prime when the two numbers only common divisor is 1 but also not print relatively prime after 1 when the numbers do have more common divisors. this the output right now.
Please enter two positive integers:
10
20
Common divisors of 10 and 20:
1
Relatively Prime
2
5
10
You need a boolean value to store whether you have found a greater-than-one divisor inside the loop. Instead of
if (i == 1)
System.out.println("Relatively Prime");
Check the boolean value after the loop and print "Relatively Prime" if a divisor was not found.
You have the line if (a % i == 0 && b % i == 0) { twice, you only need to have one of it, make sure to remove the closing brace for it as well.
If you want to print "relatively prime" only if there were no other divisors, you should check for other divisors first (for instance by starting with the large numbers and working your way down, rather than starting with small numbers and working your way up) and if you find one, somehow record this fact so you later know not print "relatively prime".
In code:
boolean divisorFound = false;
for (int i = b; i > 1; i--) {
if (a % i == 0 && b % i == 0) {
System.out.println(i);
divisorFound = true;
}
}
System.out.println(1);
if (!divisorFound) {
System.out.println("relatively prime");
}
Of course, there are more efficient algorithms. For instance, one could use euklid's algorithm to efficiently determine the greatest common divisor, then find its prime factors, and use that to efficiently iterate all divisors.
this works good but the output code is in descending order I need it ascending sadly
Actually, since we take the 1 out of the loop, the order of the loop doesn't matter anymore :-)
System.out.println(1);
boolean divisorFound = false;
for (int i = 2; i <= b; i++) {
if (a % i == 0 && b % i == 0) {
System.out.println(i);
divisorFound = true;
}
}
if (!divisorFound) {
System.out.println("relatively prime");
}
what I'm trying to do is use a while loop to check userNum % 2 > 1 once it hits one i want it to stop and print out all the values of the division so for example
if 20 is user num it would generate. 20 / 2 and 10/ 2 and 5/2 and then 2/2 resulting in 1 and then stopping
(integer division)
import java.util.Scanner;
public class DivideByTwoLoop {
public static void main (String [] args) {
int userNum = 0;
userNum = 20;
while ( (userNum % 2) > 1){
userNum = userNum / 2;
System.out.println(userNum );
}
System.out.println("");
return;
}
}
thats what I have so far.
any help is greatly appreciated.
userNum % 2 is always either 1 or 0, so the condition of the while-loop is never true. The condition should be userNum > 1 instead of (userNum % 2) > 1.
My program does not count 0 as an even number
And I don't want to use for statement just while loop
thank you
import java.util.*;
public class DigitAnalyst {
public static void main(String[] args) {
int zero=0;
int lastdigit;
Scanner inputNumber= new Scanner(System.in);
System.out.println("enter any number: ");
int number = inputNumber.nextInt();
while(number > 0)
{
int zeros=0;
int odds=0;
int evens=0;
while(number > 0)
{
number=number/10;
lastdigit=number%10;
if (lastdigit==zero)
zeros++;
if (lastdigit % 2 == zero)
evens++;
if (lastdigit % 2 != zero)
odds++;
}
System.out.println(odds +" odd digits");
System.out.println(evens +" even digits");
System.out.println(zeros +" zero digits");
}
}
}
Based on your code, it does count 0 as an even number, since 0 % 10 == 0.
Yet I think your problem comes from number=number/10; which is executed when entering the loop.
Try instead to put this statement at the end of the loop:
while (number > 0) {
lastdigit = number % 10;
// increment counters
number = number / 10;
}
I'm not entirely clear on what the problem is, but I suspect that you simply need to reorganize your logic a bit with else. Instead of this:
if (lastdigit==zero)
zeros++;
if (lastdigit % 2 == zero)
evens++;
if (lastdigit % 2 != zero)
odds++;
use this:
if (lastdigit==zero)
zeros++;
else if (lastdigit % 2 == zero)
evens++;
else
odds++;
That way, if lastdigit is zero, it won't count as either even or odd (which I'm guessing is the behavior you want).
All you need to do is instead of the three if statements, format them as this:
if (lastdigit % 2 != zero){
odds++;
}
if (lastdigit==zero) {
zeros++;
} else if (lastdigit % 2 == zero) {
evens++;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
In Java, how do I test if a character is an even or odd digit?
Here is what I have so far:
import java.util.Scanner;
public class OddOrEven{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int number, digit1, digit2, digit3;
System.out.print( "Enter three-digit number: " );// prompt
number = input.nextInt(); // read number
// determine the 3 digits
digit1 = number / 100;
digit2 = number % 100 / 10;
digit3 = number % 100 % 10;
if (digit1 % 2 == 0 && digit2 % 2 == 0 && digit3 % 2 == 0);
System.out.println( "This number contains all even digits.");
if (digit1 % 2 != 0 && digit2 % 2 == 0 && digit3 % 2 == 0);
System.out.println("This number contains both odd and even digits.");
if (digit1 % 2 != 0 && digit2 % 2 != 0 && digit3 % 2 == 0 );
System.out.println("This number contains both odd and even digits.");
if (digit1 % 2 == 0 && digit2 % 2 != 0 && digit3 % 2 == 0 );
System.out.println("This number contains both odd and even digits.");
if (digit1 % 2 == 0 && digit2 % 2 != 0 && digit3 % 2 != 0);
System.out.println("This number contains both odd and even digits.");
if (digit1 % 2 != 0 && digit2 % 2 != 0 && digit3 % 2 != 0);
System.out.println("This number contains all odd digits.");
}
}
If the number you are working with is an int (or a similar primitive type like long) then you can do something like this
int num = // something
while (num != 0) {
int digit = num % 10;
System.out.println(digit + " is " + (digit % 2 == 0 ? "even" : "odd"));
num /= 10;
}
This will iterate over the digits from right to left.
public static void main(String[] args) throws Exception {
int num = 28172;
String temp = Integer.toString(num);
int[] numArray = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
numArray[i] = temp.charAt(i) - '0';
}
for (int i : numArray) {
System.out.println("Num " + i + " is " + ((i % 2 == 0) ? "even" : "odd"));
}
}
Gives me the output:
Num 2 is even
Num 8 is even
Num 1 is odd
Num 7 is odd
Num 2 is even
First, convert the int to a String. Then, since Strings are Character arrays, you can loop through each character in the array and turn it into an Integer by subtracting the ascii Character 0. Then, you can loop through each Integer in this array, and use the mod operator (%) which will give you the remainder of a division. num%2==0 will return true if the number is even, otherwise false.
I am creating a program that asks the user for several integers and one of the statements ask the user "Enter an integer that is negative and even or positive and odd". How exactly would I go about setting up such a question? I have this so far. I have no idea how exactly I should do this, as my instructions are pretty confusing. This is what the question is for my problem:
4.
Ask the user for an integer that is either negative and even or positive
and odd. Use an if statement and compound conditional.
import java.util.Scanner;
public class ExerciseFour
{
public static void main ( String[] argsv )
{
int choice;
int choiceTwo;
int choiceThree;
Scanner input = new Scanner(System.in);
System.out.println( "Enter a number between 0 and 10" );
choice = input.nextInt();
if ( choice > 0 && choice < 10 )
{ System.out.println( "Valid number" );
}
else
{ System.out.println( "Invalid number" );
return;
}
System.out.println( "Enter a number divisible by 2 or 3?" );
choiceTwo = input.nextInt();
if ( choiceTwo % 2 == 0 && choiceTwo % 3 == 0 )
{ System.out.println( "Valid number" );
}
else
{ System.out.println( "Number not divisible by 2 or 3" );
return;
}
System.out.println( "Enter an integer that is negative and even or positive and odd (Ex. -2 or 7 )" );
choiceThree = input.nextInt();
if ( choiceThree )
{
}
else
{
}
((choiceThree > 0) && (choiceThree % 2 == 1)) || ((choiceThree < 0) && (choiceThree % 2 == 0))
The above is the compound condition you're looking for, which means:
(
(choiceThree > 0) //positive number / greater than zero
&& // AND
(choiceThree % 2 == 1) //odd number: (an odd number divided by two has a remainder of 1)
)
|| // OR
(
(choiceThree < 0) //negative number / less than zero
&&
(choiceThree % 2 == 0) //even number (an even number divided by two has a remainder of 0)
)
EDIT: % is the modulo operator.
The result of a % b is the remainder of the integer division a / b.
The key is to use The modulo operator. An even number is divisible by 2 with no remainder. So:
if (choiceThree < 0) {
if (choiceThree % 2 == 0) {
System.out.println ("Valid");
} else {
System.out.println ("Invalid");
}
} else {
if (choiceThree % 2 != 0) {
System.out.println ("Valid");
} else {
System.out.println ("Invalid");
}
}
This is a bit cumbersome, of course. A more elegant way to express this boolean logic would be by using the exclusive or (xor) operator. This operator returns true if one and only one of its operands evaluate to true:
if (choiceThree > 0 ^ choiceThree % 2 == 0) {
System.out.println ("Valid");
} else {
System.out.println ("Invalid");
}
I think there is a mistake in the second question
choiceTwo % 2 == 0 && choiceTwo % 3 == 0
you may want to write || instead of && becouse you sad devisible to 2 OR 3 ;-)
For your other problem: You have two boolean expressens wich may be true:
Ask the user for an integer that is either negative and even
(choiceThree < 0 && choiceThree % 2 == 0)
or positive and odd.
(choiceThree > 0 && choiceThree % 2 == 1)
Use an if statement and compound conditional.
So just combine these to statements with a logical OR (||)
Create a method that returns true if it's one of those scenarios:
public boolean isCorrectInteger(int number){
if ((number < 0) && (number % 2 == 0)) { //negative and even
return true;
} else if((number < 0) && (number % 2 == 1)) { // positive and odd
return true;
} else { // other cases
return false;
}
}
This can be written in a one bigger condition, I've just split it into two for the sake of a simple example.
Also take into consideration that zero is currently assigned neither to positive nor negative - you can change this as you please by using the <= or >= operators.
Try this:
System.out.println( "Enter an integer that is negative and even or positive and odd (Ex. -2 or 7 )" );
choiceThree = input.nextInt();
if ( (choiceThree>0 && choiceThree%2==1) || (choiceThree<0 && choiceThree%2==0) )
{
System.out.println("Correct");
}
else
{
System.out.printlnt("ERROR");
}