这个if判断为什么是执行?如何求范围内的素数?

这里运行的结果是错误的,原因是if判断不执行,这里的if判断为什么不执行。

import java.util.Scanner;

/*
 * 判断101-200之间有多少个素数,并输出所有素数
 */
public class IfPrimeNumber {
    //numberOfPrime用来计算访问内的素数个数
    int numberOfPrinme;
    /*
     * firsIndex 该范围内的开头
     * endIndex 该范围内的结尾
     * staticFirstIndex 用来被firstIndex遍历
     */
    int firstIndex, endIndex, staticFirstIndex;
/*
 * 用来获取输入
 */
    public void inPut() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入开头:");
        firstIndex = scanner.nextInt();
        System.out.print("请输入结尾:");
        endIndex = scanner.nextInt();
    }
/*
 * 判断范围内的素数,并且将其打印出来
 */
    public void ifPrime() {
        staticFirstIndex = firstIndex;
        for (; firstIndex <= endIndex; firstIndex++) {
            for (; staticFirstIndex < firstIndex; staticFirstIndex++) {
                /*
                 * 这里的if判断不执行
                 */
                if (firstIndex % staticFirstIndex == 0) {
                    break;
                }
            }
            if (staticFirstIndex >= firstIndex) {
                numberOfPrinme++;
                System.out.print(firstIndex + "\t");
            }
        }
        System.out.println("\n其中有" + numberOfPrinme + "个素数");
    }

    public static void main(String[] args) {
        IfPrimeNumber ifPrimeNumber = new IfPrimeNumber();
        ifPrimeNumber.inPut();
        ifPrimeNumber.ifPrime();
    }
}


运行结果:

img

运行的结果是错的,最后检查是if判断没有执行,这个if判断为什么没有执行?如何求范围内的素数?

for (; staticFirstIndex < firstIndex; staticFirstIndex++)这里改成
for (staticFirstIndex = 2; staticFirstIndex < firstIndex; staticFirstIndex++)

我觉得是你第二个for循环没有执行。而且staticFirstIndex 始终等于 firstIndex;所以39行if始终成立,所以才会有100个素数
ifPrim() 建议如下修改

public void ifPrime() {
       // staticFirstIndex = firstIndex;
        for (; firstIndex <= endIndex; firstIndex++) {

            boolean isPrime = true;
            //以下判断firstIndex是不是素数
            //从2到firstIndex试除(firstIndex不需要除)
            for (int n = 2; n < firstIndex; n++) {
                /* 
                 * 这里的if判断不执行
                 */
                if (firstIndex % n == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                numberOfPrinme++;
                System.out.print(firstIndex + "\t");
            }
        }
        System.out.println("\n其中有" + numberOfPrinme + "个素数");
    }