public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter value: ");
int value = input.nextInt();
if (value == 1 || value == 3 || value == 5 ||value == 7 || value == 9) {
if (value % 3 == 0)
System.out.println(value + " is an odd number less than 10"
+ " and divisible by 3");
}
else if (value == 2 || value == 4 || value == 6 ||value == 8) {
if (value % 3 == 0)
System.out.println(value + " is an even number less than 10"
+ " and divisible by 3");
}
else
System.out.println("Invalid number");
input.close();
}
if-else statement only recognizes integers that are divisible by 3 which are 3, 6 or 9. When I type 1 or 5, for example, the programme does not display any of the input and just stop running.
If you type "1" then if(value == 1) is true so then the program checks if(value %3 == 0). Since value%3 is 1 when value is 1 it doesn't print anything and exits. So you see nothing.
Normally, in any IDE there are some debugging facilities so by using them you will be able to see how the program works step by step.
I don't know why you used this particular logic in your if statements, but we can refactor assuming what you print is actually what you want:
is an odd/even number less than 10 and divisble by 3
if (value < 10 && value % 2 == 1 && value % 3 == 0) {
System.out.println(value + " is an odd number less than 10"
+ " and divisible by 3");
}
else if (value < 10 && value % 2 == 0 && value % 3 == 0) {
System.out.println(value + " is an even number less than 10"
+ " and divisible by 3");
}
else {
System.out.println("value does not meet our conditions.");
}
The immediate reason why 1 and 5 apparently cause the code to do nothing is that they enter the first if statement but then fail the next condition as they are not divisible by three, and your code does not output in this case.
This happens because of the given logic. When you type 1 or 5 as input first outer if becomes true. But if(value % 3 == 0) isn't true, that's why program ended up without giving any output.
If I understand your expectation of this program correctly please try the following code
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter value: ");
int value = input.nextInt();
if (value < 10 && value % 2 == 0 && value % 3 == 0) {
System.out.println(value + " is an even number less than 10" + " and divisible by 3");
}
else if (value < 10 && value % 2 != 0 && value % 3 == 0) {
System.out.println(value + " is an odd number less than 10" + " and divisible by 3");
}
else
System.out.println("Invalid number");
input.close();
}
when you enter 1 or 5 for example, below condition becomes true
if (value == 1 || value == 3 || value == 5 ||value == 7 || value == 9)
however, value %3 is not equal to 0 hence nothing is printed and program control directly goes to
input.close();
First of all, you should not use if-else statements that way. Now, the problem is that when you enter 1 or 5, they pass the first if statement, but neither (1 % 3 ==0) or (5 % 3 == 0) will be true, and that is why your code does nothing in those cases. Try this instead:
if(value % 3 == 0 && value <10) {
if(value % 2 != 0){
System.out.println(value + " is an odd number less than 10"
+ " and divisible by 3");
}else{
System.out.println(value + " is an even number less than 10"
+ " and divisible by 3");
}
}else{
System.out.println("Invalid number");
}
Related
I have this assignment:
Write a Java program which finds all the odd numbers from 1 - 50 which are divisible by 7, but sums only the EVEN numbers which are divisible by 9.
Print sum.
Print count of odd numbers which are divisible by 7.
Print count of even numbers which are divisible by 9 within that range.
This is my code:
int sNumber = 0;
for(int aNumber= 1; aNumber <= 50; aNumber++)
{
if (aNumber % 7 == 0)
if(aNumber % 2 == 1)
System.out.println("These are odd"+" "+ aNumber);
}
for(int bNumber=1 ; bNumber < 50; bNumber++)
{
if (bNumber % 9 == 0)
if(bNumber%2 == 0)
System.out.println("These are even"+" "+bNumber);
}
I'm stuck with putting bNumbers into sum form, any help?
The idea is to start with creating a variable to store the sum. It has to start from 0. Whenever you find an even number that is divisible by 9, you add it to the sum. By the end of your for loop when you have iterated through all of your numbers, you would have the total of all your even numbers that are divisible by 9 in your variable sum.
In my code below, I have also used two integers countEven and countOdd to keep track of the number of relevant numbers found. counteven increments by one whenever an even number that is divisible by 9 is found and countodd increments by one whenever an odd number that is divisible by 7 is found.
Note: it is always good practice to use braces for all for, if, while and other similar statements / loops, even if the block contains only one line of code to execute.
int countEven = 0, countOdd = 0, sum = 0;
for(int i= 1; i <= 50; i++){
if ((i % 7 == 0) && (i % 2 == 1)) {
System.out.println("This is an odd number that is divisible by 7: " + i);
countOdd++;
}
if ((i % 9 == 0) && (i % 2 == 0)) {
System.out.println("This is an even number that is divisible by 9: " + i);
countEven++;
sum += i;
}
}
System.out.println("These are " + countOdd " odd numbers thare are divisible by 7 and " + countEven + " even numbers that are divisible by 9.");
System.out.println("Sum of even numbers that are divisible by 9: " + sum);
You don't need two loops to do this, it can be done in one.
Check the current number vs. the two conditions you have:
if(i % 2 == 0 && i % 7 == 0)
sumOfEven += i;
if(i % 2 != 0 && i % 9 == 0)
countOdd++;
You need to simply add this to your second loop sNumber += bNumber;
Also consider using AND operator instead of nested if statement.
int sNumber = 0;
for (int aNumber = 1; aNumber <= 50; aNumber++) {
if (aNumber % 7 == 0 && aNumber % 2 == 1) {
System.out.println("These are odd" + " " + aNumber);
}
}
for (int bNumber = 1; bNumber <= 50; bNumber++) {
if (bNumber % 7 == 0 && bNumber % 2 == 1) {
System.out.println("These are even" + " " + bNumber);
sNumber += bNumber;
}
}
System.out.println("Sum of even numbers" + " " + sNumber);
Hope this helps.
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.
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
Hello so I am attempting to write a code that test the operators and need a little help declaring variables.
So in my code under my if statement I declare a certain answer to be true or false depending on what the entered number would be and I keep getting stuck on the "cannot find symbol" error. Here is my code
import java.util.Scanner;
public class TestOperators
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
//prompt the user to enter an integer
System.out.print("Enter an integer: ");
int num = input.nextInt();
String t = new String("True");
String f = new String("False");
//calculate
if ((num % 5 == 0) && (num % 6 == 0))
answer = t;
else if ((num % 5 == 0) && (num % 6 != 0) || (num % 5 != 0) && (num % 6 == 0))
answer = t;
else if ((num % 5 == 0) || (num % 6 == 0))
answer = t;
else
answer = f;
//print results
System.out.println("Is " + num + " divisible by 5 and 6? " + answer);
System.out.println("Is " + num + " divisible by 5 or 6?" + answer);
System.out.print("Is " + num + " divisible by 5 or 6, but not both?" + answer);
}
}
The program tells me that I cannot declare the variable "answer" in that spot. I am trying to tie the string "f" and "t" variables to the answer variable and dont know how. Please help!
You're not declaring the variable at all. You're just trying to assign to it. You can just add
String answer;
to the code before you start trying to assign to it.
Additionally, you almost never want to call new String(String), and you can simplify your code significantly. You'd be better off determining the result (e.g. just with ||) and then converting the result into a string:
boolean result = ((num % 5 == 0) && (num % 6 == 0)) ||
((num % 5 == 0) && (num % 6 != 0) || (num % 5 != 0) && (num % 6 == 0)) ||
((num % 5 == 0) || (num % 6 == 0));
String answer = result ? "True" : "False";
Looking at that, the result you want actually seems to be as simple as:
String answer = (num % 5 == 0 || num % 6 == 0) ? "True" : "False";
The only way you can get "False" as an answer in both your original code and my final code is if the number isn't divisible by either 5 or 6.
Your code just expresses that in a really complicated way...
You never declared answer. Try adding this line at the beginning of the method:
String answer;
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");
}