2021年3月12日星期五

Find even numbers between interval but exclude multiples of random number in Java

I've started to learn Java very recently, and got a couple of exercises to practice. Been struggling with this one: I have to obtain 2 random numbers, A and B, and have to print all even numbers between 1 and B. I managed to do this part, but then comes the rest of the question: If a divisor of 2A is found, the program must break and show the following message: "Multiple of 2A found". All I could do was print every even number between 1 and B, and exclude every multiple of 2A, like this:

import java.util.Random;    public class JavaExercise {        public static void main(String[] args) {          Random random = new Random();          int A = random.nextInt(9) + 1;          int B = random.nextInt(99) + 1;                    for (int i = 1; i <= B; ++i) {               if ((i % 2 == 0) && (i % (2*A) != 0))                    System.out.println (i);               else                   break;                            }        }    }  

But I need the program to break when it finds a multiple of 2*A, and shows the message above. Tried doing like this, but got a really terrible output, showing the message many times instead of once,:

        for (int i = 1; i <= B; ++i) {              if (i % 2 == 0)                   System.out.println (i);                  if (i % (2*A) == 0)                      break;                      System.out.println("Multiple of 2A found");                            }  

Would anyone help me finding out where am I going wrong? I'd appreciate!

https://stackoverflow.com/questions/66609153/find-even-numbers-between-interval-but-exclude-multiples-of-random-number-in-jav March 13, 2021 at 09:04AM

没有评论:

发表评论