java - java中的返回问题

标签 java return conditional-statements

所以我正在用 Java 为 codeeval 编写一个 mersense 脚本来练习这门语言(我对它还很陌生)。有一次我检查数字是否为质数,在我的方法中我进行了正常检查,一切看起来都很好

public static boolean isPrime (int testValue){
  if (testValue < 4){
    return true;
  } else if (testValue % 2 == 0){
    return false; 
  } else {
    for (int I = 1; I < Math.sqrt (testValue); I++){
      if (testValue % I == 0 ){
         return false; 
     }
   }
   return true;
  }
}

然而,唯一通过的似乎是 1 和 3。我可以在 for 循环之后不做那个 return 吗?这是怎么回事?有什么想法吗?

编辑:

完整代码如下:

import java.io.*;
import java.lang.Math;

public class Main{
public static void main(String[] args) throws IOException {
    File file = new File(args[0]);
    BufferedReader buffer = new BufferedReader(new FileReader(file));
    String line;
    int n;
    StringBuilder result = new StringBuilder();
    int candidate;
    while((line = buffer.readLine()) != null){
        n = Integer.parseInt(line.trim());
        for(int i = 1; i < n; i++){
            candidate = mersenne(i);
            if(isPrime(candidate)){
                System.out.println(candidate + " "+ isPrime(candidate));
                if((i+1) >= n){
                    result.append(candidate);
                }else{
                    result.append(candidate + ", ");
                }
            }
        }
        System.out.println(result.toString());
        result = new StringBuilder();
    }
}

public static int mersenne (int testValue){
    return (int)Math.pow(2,testValue) - 1;
}
public static boolean isPrime(int testValue){
    if(testValue < 4 && testValue > 1){
        return true;
    }else if(testValue % 2 == 0){
        return false;
    }else{
        for(int i = 3; i <= Math.sqrt(testValue); i++){
            if(testValue % i == 0){
                return false;
            }
        }
        return true;
    }
}
}

最佳答案

你从 1 开始循环。所有 % 1 都是 0。从 3 开始。

关于java - java中的返回问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38938455/

相关文章:

java - 在 ExecutorService 中跟踪已完成的任务

Python Pandas groupby : how to do conditional aggregation dependent on other column

c - 这段代码发生了什么

c++ - 在 C++ 中填充并返回读取的数据

c++ - "if(T t = ...) { } else return t;"的优雅方式?

java - 关于旋转text3d

java - Java Swing GUI错误

java - 正确使用 BitSet 来替换基于 int 的标志。是否可以?

返回语句

c - 返回的字符串值变成垃圾