简体   繁体   中英

Java - Why won't my prime number program print the last number?

I'm supposed to write a program for a Java Intro class that lists the prime numbers up to the number a user inputs. However, with the code I have, if the user inputs a prime number, my program won't list back that number, even though it's supposed to do so when it's prime. Could someone give me a hint as to why it's not working?

    int userNum=kbd.nextInt();
    if (userNum<2){
        System.out.println("Not a valid number.");
        System.exit(1);
    }
    System.out.println("The prime numbers up to your integer are:");
    for (int num1 = 2; num1<userNum; num1++) {   
        boolean prime = true;


        for (int num2 = 2; num2 < num1; num2++) {
            if (num1 % num2 == 0) {
                prime = false;
                break; 

            }
        }

        // Prints the number if it's prime.
        if (prime) {
            System.out.print(num1 + " ");
        }
    }

For example, when I input "19," the program prints all prime numbers up to and including "17." Thanks!

You need num1 to take the value userNum as the last value to check.

Therefore, you need to replace num1 < userNum with num1 <= userNum .

Your loop has a condition of num1 < userNum . This means that it allows all numbers below userNum . What you appear to want is all numbers below and including userNum , so you want num1 <= userNum .

The start of your loop would thus be this:

    for (int num1 = 2; num1 <= userNum; num1++) {   

Change this

num1<userNum

to

num1<=userNum

At the moment you stop before the two numbers are equal in your for loop.

将for语句的结束条件更改为num1 <= userNum。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM