发布网友
共1个回答
热心网友
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class T2 {
public static void main(String[] args) {
new T2().judge1();
new T2().judge2();
}
public void judge1(){
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("请输入一个数字");
String str = br.readLine();
int a = Integer.parseInt(str);
if(isPrimes(a)){
System.out.println(a+" 是素数");
}else{
System.out.println(a+" 不是素数");
}
}catch(NumberFormatException e){
System.out.println("只能是数字");
judge1();
}catch (IOException e) {
System.out.println("读取出错了");
}
}
private void judge2() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("请输入两个数用,号隔开(一个范围)");
String str = br.readLine();
String [] s = str.split(",");
int a = Integer.parseInt(s[0]);
int b = Integer.parseInt(s[1]);
isPrimes2(a, b);
}catch(NumberFormatException e){
System.out.println("格式不正确");
judge2();
}catch (IOException e) {
System.out.println("读取出错了");
}
}
private void isPrimes2(int a, int b) {
System.out.println(a+"-"+b+"范围的素数有:");
for(int i=a;i<=b;i++){
if(isPrimes(i)){
System.out.print(i+",");
}
}
}
public static boolean isPrimes(int n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}