import java.io.*;
public class Sushu
{
public static void main(String[] args)
{
String Str="";
System.out.println("请输入一个数:");
try{
BufferedReader in=new BufferedReader(new
InputStreamReader(System.in));
String s=in.readLine();
int n=Integer.parseInt(s);
for (int i=2;i<n ;i++ )
{
if(n%i==0)
{
 Str="不是";
 }
else
{
 Str ="是";
}
}
System.out.println(n+Str+"素数");
}catch(IOException e){}
}
}不管输入什么数,输出的都说是素数!请问高手,错在哪里??是在if里面吗?

解决方案 »

  1.   

    if(n%i==0)
    {
    Str="不是";
    break;
    }
      

  2.   

    是没跳出循环 也就是说当判断不是素数时 就应该停止for循环 既然判断已经不是素数了 接下去判断已经没有意义了 另外给楼主参考个写法 希望对楼主有帮助:public class PrimeNumber {
    public static void main(String[] args) {
    for (int i = 2; i <= 100; i++) {
    boolean flag = true;
    for (int j = 2; j <= Math.sqrt(i); j++) {
    if (i % j == 0) {
    flag = false;
    break;
    }
    }
    if (flag) {
    System.out.print(i + " ");
    }
    }
    }
    }这是判断1-100之间有几个素数的写法
      

  3.   

    import java.io.*;
    public class Sushu
    {
    public static void main(String[] args)
    {
    String Str="";
    System.out.println("请输入一个数:");
    try{
    BufferedReader in=new BufferedReader(new
    InputStreamReader(System.in));
    String s=in.readLine();
    int n=Integer.parseInt(s);
    for (int i=2;i<n ;i++ )
    {
    if(n%i==0)
    {
    Str="不是";
    break;}//这样就可以了
    else
    {
    Str ="是";
    }
    }
    System.out.println(n+Str+"素数");
    }catch(IOException e){}
    }
    }