分配是关于尝试从用户输入的内容中获取素数,并且我试图通过用户输入0来结束循环
/*
Natasha Shorrock
Assignment A4
10/20/16
*/
package a4;
import java.util.Scanner;
public class MainApp {
static boolean isPrimeOptimized(int candidate) {
if (candidate < 2) {
return false;
}//if
if (candidate % 2 == 0) {
//divisble by 2 with no remainder
//is not prime
return false;
}//if
int divisor = 3;
while (divisor < candidate / 2) {
if (candidate % divisor == 0) {
return false;// this is not prime
}//if
divisor = divisor + 2;
}//while
return true;
}//isPrime
public static void main(String[] args) {
while (true) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 2 numbers or zero to exit: ");
//ask the user for low and high
//range of [prime numbers to generate
int low = sc.nextInt();
int high = sc.nextInt();
int candidate = low;
int count = 0;
while (candidate <= high) {
if (isPrimeOptimized(candidate)) {
//if prime print
count = count + 1;
System.out.println();
System.out.println(count + " " + candidate);
}//if
candidate = candidate + 1;
}//while
}//while (true)
}//class
}//classMainApp
答案 0 :(得分:0)
由于您只需要退出一个号码0
,因此只会填充low
并等待high
。因此if
应位于两次扫描之间,并且只应检查low
在if
下添加low
语句,以检查它是否为0。
int low = sc.nextInt();
if(low == 0){
break;
}
答案 1 :(得分:0)
首先,即使用户输入0,您也要强制他们输入两个数字:
int low = sc.nextInt();
int high = sc.nextInt();
我建议你在代码中执行以下操作:
int low = sc.nextInt();
if(low==0){
return 0;
} else{
int high = sc.nextInt();
//rest of your code and while loop
}