loops - 如何创建最终停止的循环

到目前为止,是这个代码


import java.util.Scanner;//Importing the scanner



public class Assignment4 {


 public static void main(String[] args) {


 Scanner scan = new Scanner(System.in);//Creating the scanner



 int number;



 System.out.println("Enter a positive integer. Enter '-1' to quit.");//Asking the user to input a number


 number = scan.nextInt();//Scanning for the number



 if(number>0);{


 boolean prime = true;


 for(int j = 2; j <= number/2; ++j)


 {


 if(number % j == 0)//To see if the number is prime


 {


 prime = true;//If the equation is true, it's a prime number


 break;


 }


 }


 if (prime)//If its a prime number


 System.out.println(number +" is a prime number.");


 else//If it is not a prime number


 System.out.println(number +" is not a prime number.");


 }



 if(number==(-1))//If the user inputs -1


 {


 System.exit(0);//Exiting the program


 }


 }


}



时间:

那是因为你的程序里没有循环,可以使用:


while(number>0){


...


}



而不是if(number

...