Java 如何在循环结束后打印另一个术语?在爪哇

Java 如何在循环结束后打印另一个术语?在爪哇,java,primes,Java,Primes,我的要求是,我需要检查“secondnum”输入是否为素数,如果不是素数,则打印下一个素数 例如: import java.util.Scanner; public class PrimeNumbers { public static boolean prime(int num) { boolean flag = true; for(int i=2;i<=num/2;i++) { if(num%i==0) {

我的要求是,我需要检查“secondnum”输入是否为素数,如果不是素数,则打印下一个素数

例如:

import java.util.Scanner;

public class PrimeNumbers {
    public static boolean prime(int num) {
        boolean flag = true;
        for(int i=2;i<=num/2;i++) {
            if(num%i==0) {
                flag = false;
                break;
            }

        }
        return flag;
    }
    public static void main(String[] args) {
        String separator = "";
        Scanner scan = new Scanner(System.in);
        System.out.println("First num:");
        int low = scan.nextInt();
        System.out.println("Second num:");
        int high = scan.nextInt();
        if(low>high||high<=0||low<0||(high-low) == 1) {
            System.out.println("Invalid input");    
            System.exit(0);
        }
        while(low<high) {
            if(prime(low)==true) {
                System.out.printf(separator+"%d",low);
                separator = ",";
            }
            low++;
        }

    }
}
first num:1
second num:10
Output: 1,2,3,5,7

在第二个例子中,第二个num应该是什么?对不起,它是10。
first num:1
second num:
Output: 1,2,3,5,7,11
int lastNumber = high;
if(!prime(lastNumber)) 
{
  while(!prime(++lastNumber));
  // now you have to prime number after the high or that number itself if it 
  //is the prime
}
// now print all numbers and lastNumber in the last


You did num/2 if the first loop which is good for performance but you can increase 
performance even more you can do int sqrt = sqrt(num) , now cast it to int and use it 
int the loop
so if num is 100 in your case you will be doing 50 checks , but in sqrt case on 10 
checks