【发布时间】:2015-09-06 14:00:15
【问题描述】:
我有一个任务告诉我要执行以下操作:
创建一个名为 IsPrime() 的方法,该方法接受一个正整数作为参数。如果是素数,则该方法应返回 true。 (素数只能被 1 和它自己整除)。将此方法合并到名为 MyMathMethods 的类中。在名为 MainFile 的单独类中创建 main() 方法,该方法将通过使用输入对话框向用户询问数字来测试 IsPrime(),然后报告该数字是否为素数。
如何连接这两个文件? 这是我的代码:
package x;
import java.util.Scanner;
public class MyMathMethod
{
public static boolean isPrime(int num)
{
int result=0;
System.out.println("enter no");
Scanner s = new Scanner(System.in);
num =s.nextInt();
long sqrt = (int) Math.sqrt(num);
for(long divisor = 2; divisor <= sqrt; divisor++)
{
if(num % divisor == 0)
{
// This only needs to happen once
// for this number to NOT be prime
return false;
}
}
// If we get here, the number is prime.
return true;
}
}
另一个文件是
import x.*;
package y;
public class MainFile {
public static void main(String [] args) {
boolean isNumberPrime;
int num;
MyMathMethod methods = new MyMathMethod();
isNumberPrime = methods.isPrime(num);
{
如果(数字=真) System.out.println(num + " 是质数"); 别的 System.out.println(num + " 不是质数"); } } }
提前致谢。
【问题讨论】: