Java getting a sum from If statement - java

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.

Related

How can I make it so my while-loop only prints even numbers? Java Eclipse IDE

Beginner here. For my coding class, we have an assignment that requires us to print numbers 1-20, but configure it so that it only outputs even numbers. Here is what I have so far but I'm quite stuck. He says to put an if statement and use the "%" operator but I've no idea where to put them.
int counter = 1;
System.out.println("Part 2 - Even Numbers");
while (counter <= 20)
{
//if (counter
System.out.printf("%d ", counter);
counter++;
} // end while loop
Instructions for assignment
My Output
CORRECT Output
if(counter % 2 == 0){
System.out.printf("%d ", counter);
}
counter++;
% operator is mod operator, if counter % 2 == 0 , then counter is an even number
% is an arithmetic operator, it is called MODULO.
Modulo operator returns the remainder of 2 numbers. In this case, we use a modulo to find out whether a number is even or odd.
odd%2 returns 1
even%2 returns 0
The while loop loops through the first 20 elements. So we put an if statement before printing the element. If the counter is an even number i.e (counter%2 == 0) we print that.
This is the code that prints even numbers:
int counter = 0;
System.out.println("Part 2 - Even Numbers");
while (counter <= 20)
{
if (counter%2 == 0){
System.out.printf("%d ", counter);
}
counter++;
} // end while loop
This can also be done without using MODULO operator:
int counter = 0;
System.out.println("Part 2 - Even Numbers");
while (counter <= 20)
{
System.out.printf("%d ", counter);
counter+=2;
} // end while loop
use fori
public static void main(String[] args) {
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
}
% is the remainder operation

Questions about moduls and return statement

I have two questions about this of code.
Can someone explain me, what the if statement is doing exactly. I know that count has to increment every time the test is true, but I'm not sure what the this n % i == 0 is doing.
My second question is, how can I print the return statement's answer on the console?
int n = 10;
countFactors(n);
}
public static int countFactors(int n){
int count = 0;
for (int i = 1; i <= n; i++){
if (n % i == 0) //this line
count++;
}
return count;
}
}
It count the number of divisor in your range 1-n so for example :
if n = 10 the result will be 4 because there are 4 divisor:
1
2
5
10
and about how you print in console :
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
count++;
System.out.println(i);
}
}
System.out.println("Number or disivor = " + count);
You can learn here : Table of divisors
Well, as the name of the method suggests, the count represents the number of divisors that n has.
The if statement tests the following: Is n divisible by i?. in other words: Is n/i a whole number?
if you were to use:
if(n%i == 1)
instead, then it would count the numbers for which: n/i has a remainder of 1.
in order to print the return statement, you can add this line just before the return:
public static int countFactors(int n){
int count = 0;
for (int i = 1; i <= n; i++){
if (n % i == 0)
count++;
}
System.out.println(count);//adding this
return count;
}
The % operator (known as the remainder or Modulus operator) basically divides a number by another and gives you the remainder and nothing else. For instance, if you do 4 % 2, it would give you 0 because 2 goes into 4 evenly. If you would do 4 % 3 it would give you 1 because that's the remainder of 4 / 3. Also look at this website: http://www.cafeaulait.org/course/week2/15.html
The countFactors method loops 1 to n and includes n. If you do 10 % 1, you would get 0 because one goes into 10 evenly so the count would be incremented.

Java: How to test if individual characters are even or odd? [closed]

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.

Need help using random numbers and modulos

I'm trying to make a simple program that will display 20 random numbers between 1 and 100 and then print out which numbers are divisible by 3 and equivalent to 1%3 and 2%3. It seems to work just fine but I've noticed it only works with the very last number in the list. What am I missing to include all the numbers in the search for my math? Thank you in advance for any help I can get!
import java.util.Random;
public class Lab5 {
public static void main(String[] args) {
Random rnd = new Random();
int repeat = 19;
int n = 0;
for(int i=0;i<=repeat;i++){
n = rnd.nextInt(100)+1;
System.out.print(n+", ");
}
System.out.println();
System.out.println("-------------------------------------");
if(n % 3 == 0){
System.out.println("Numbers divisible by three: "+n+(", "));
}else{
System.out.println("Numbers divisible by three: NONE");
}
System.out.println("-------------------------------------");
if(n == 1 % 3){
System.out.println("Numbers equivalent to one modulo three: "+n+(", "));
}else{
System.out.println("Numbers equivalent to one modulo three: NONE");
}
System.out.println("-------------------------------------");
if(n == 2 % 3){
System.out.println("Numbers equivalent to two modulo three: "+n+(", "));
}else{
System.out.println("Numbers equivalent to two modulo three: NONE");
}
}
}
It is only printing the last number because the check if the number is divisible, etc is not in your for loop at the top. Simply copy and paste all of the code below it into your for loop and it should work as you intended.
You also have an error here: if (n == 1 % 3), it is legal but will check if n is equal to the remainder of 1 / 3. I don't think that is what you wanted to achieve, so correct it like this: if (n % 3 == 1) as Ypnypn suggested.
Your n is declared outside of the loop body, so its value will persist. However, since you are overwriting n in each loop iteration, only the last value of n will persist and will be used by other parts of the program.
As Ypnypn has said, correct your use of modulo, and as Arbiter and deanosaur have suggested, move the rest of the program logic inside the for loop
The correct syntax for modulus is n % 3 == 2. The current code n == 2 % 3 means n == 0, since the order of operations in Java requires that modulus is evaluated before equality.
You are putting all the output statements (System.out.println()) outside your loop, so it only outputs the last value.
Move your output statements so they are inside your loop:
public static void main(String[] args) {
Random rnd = new Random();
int repeat = 19;
int n = 0;
int[] numbers = new int[3]; // To hold how many numbers have modulo 0, 1 or 2
for(int i = 0; i <= repeat; i++) {
n = rnd.nextInt(100)+1;
System.out.print(n+", ");
if(n % 3 == 0)
System.out.println("The number " + n + " is divisible by 3");
else
System.out.println("" + n + " modulo 3 = " + n % 3);
numbers[n % 3]++;
}
System.out.println("Numbers divisible by 3: " + numbers[0]);
System.out.println("Numbers with modulo 3 = 1: " + numbers[1]);
System.out.println("Numbers with modulo 3 = 2: " + numbers[2]);
}
Well .. you did not calculate anything in the loop, so your print statements work the last value of n after you exited the loop. Try something like
package com.example.modulo;
import java.util.Random;
public class Modulo {
public static void main(String[] args) {
Random rnd = new Random();
int repeat = 19;
int n = 0;
int[] nMod = new int[3];
nMod[0] = 0;
nMod[1] = 0;
nMod[2] = 0;
for (int i = 0; i <= repeat; i++) {
n = rnd.nextInt(100) + 1;
nMod[n%3] = nMod[n%3] + 1;
System.out.print(n + " (" + n%3 + "), ");
}
System.out.println();
System.out.println("-------------------------------------");
System.out.println("Numbers divisible by three: " + nMod[0] + (", "));
System.out.println("Numbers equivalent to one modulo three: " + nMod[1] + (", "));
System.out.println("Numbers equivalent to two modulo three: " + nMod[2] + (", "));
}
}

How to check if an integer can be divided by 3

How to check if my integer can be divided by 3 as below:
for(int i=0; i<24; i++){
//here, how to check if "i" can be divided by 3 completely(e.g. 3, 6, 15)?
}
Use the modulo operator.
if(i % 3 == 0)
Also see Modulo operation at Wikipedia
If you are using a loop, you can use the fact that every third number can be divided by 3.
for(int i = 0; i < 24; i += 3) {
System.out.println(i + " can be divided by 3");
System.out.println((i+1) + " cannot be divided by 3");
System.out.println((i+2) + " cannnot be divided by 3");
}
This avoids the need for a modulo and cuts the number of loops by a factor of 3.
Use the MOD operator
for(int i=0; i<24; i++){
if( i%3 == 0 )
// It is divisible by 3
}
Well, what you could do (it might be a bit faster; it is faster on my machine) is:
boolean canBeDevidedBy3 = ((int) (i * 0x55555556L >> 30) & 3) == 0;
instead of
boolean canBeDevidedBy3 = (i % 3) == 0;
However, the multiplication trick only works for -2 <= i <= 1610612735. This answer was inspired by this optimization question. But if I can give you a tip: use (i % 3) == 0. It's so much simpler, and will always work.
Check the remainder of i devided by 3
if (i % 3 == 0) {}
inside the loop:
if (i%3 == 0)
// it can be divided by 3
% is called "mod" or "modulus" and gives you the remainder when dividing two numbers.
These are all true:
6 % 3 == 0
7 % 3 == 1
7 % 4 == 3
if( i % 3 == 0 )
The % operator delivers you the rest of the division i / 3
if( i % 3 == 0 ){
System.out.println("can be divided by 3");
}else{
System.out.println("cant divide by 3");
}
Is this question for real?

Categories

Resources