import java.io.*;
public class MathEx {
/**
* Creates a new instance of <code>MathEx</code>.
*/
public static void checkPrime(int num){
boolean isPrime=true;
int i=0;
for(i=2;i<=Math.sqrt(num);i++){
if(num%i==0)
{isPrime=false;
break;}
if(isPrime)
System.out.println(num+"是质数");
else
System.out.println(num+"不是质数");
}
}
public MathEx() {
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception{
// TODO code application logic here
System.out.print("请输入1个整数:");
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int num=Integer.parseInt(br.readLine());
br.close();
isr.close();
MathEx.checkPrime(num);
}
}结果:请输入1个整数:15
15是质数
这个是正确的,
但是如果输入16,16不是质数
结果:
请输入1个整数:16Process completed
为什么不输出“16不是质数”呢?
解决方案 »
- java openConnection()对象是指什么
- ?新手请教编程中一个问题!
- 关于super的疑惑
- JFileChooser 保存文件时根据选择的文件类型改变文件后缀名
- Struts数组提交问题
- 一个j2se问题,哪位高手帮我解答下,谢谢!
- 一个简单的问题-(j & 0xff) << 24 | i & 0xffffff 中的“0xff”和“0xffffff”起什么作用?
- String str=new String("a")和String str = "a"有什么区别?
- JTABLE中列单元事件处理问题
- 68分只有这么多了,帮我解决一个困我几天的问题
- 大家进来帮下忙
- 求助,新弹出的窗口无法正常显示
import java.io.*;
public class MathEx {
/**
* Creates a new instance of <code>MathEx</code>.
*/
public static void checkPrime(int num){
boolean isPrime=true;
int i=0;
for(i=2;i<=Math.sqrt(num);i++){
if(num%i==0)
{isPrime=false;
break;}
}
if(isPrime)
System.out.println(num+"是质数");
else
System.out.println(num+"不是质数");
}
public MathEx() {
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception{
// TODO code application logic here
System.out.print("请输入1个整数:");
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int num=Integer.parseInt(br.readLine());
br.close();
isr.close();
MathEx.checkPrime(num);
}
}
程序帮你稍微改了一下public class PrimeTest { /**
* Creates a new instance of <code>MathEx</code>.
*/
public static void checkPrime(int num) {
boolean isPrime = true;
int i = 0;
for (i = 2; i < num; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime)
System.out.println(num + "是质数");
else
System.out.println(num + "不是质数");
} /**
* @param args
* the command line arguments
*/
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.out.println("A number is required to run this program.");
} int num = Integer.parseInt(args[0]);
PrimeTest.checkPrime(num);
}
}