简体   繁体   English

Java-为什么我的素数程序不会显示最后一个数字?

[英]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. 我应该为Java Intro类编写一个程序,该程序列出素数直至用户输入的素数。 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." 例如,当我输入“ 19”时,程序将打印所有素数,直到“ 17”。 Thanks! 谢谢!

You need num1 to take the value userNum as the last value to check. 您需要num1才能将值userNum作为要检查的最后一个值。

Therefore, you need to replace num1 < userNum with num1 <= userNum . 因此,您需要将num1 < userNum替换为num1 <= userNum

Your loop has a condition of num1 < userNum . 您的循环的条件为num1 < userNum This means that it allows all numbers below userNum . 这意味着它允许userNum以下的所有数字。 What you appear to want is all numbers below and including userNum , so you want num1 <= userNum . 您似乎想要的是下面的所有数字,包括userNum ,所以您想要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循环中两个数字相等之前停止。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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