[英]prime numbers test in java
我有一项任务告诉我要执行以下操作:
创建一个名为 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);
{
if(num=true) System.out.println(num + "是质数"); else System.out.println(num + " 不是质数"); } } }
提前致谢。
您想在另一个类中从 main 中调用方法 isPrime() 吗?
当它们在同一个包中时,您必须创建类 MyMathMethods 的新实例并调用方法 isPrime()。 当它们在不同的类中时,您必须导入缺少的类并执行与上述相同的操作。 如果您不手动导入它,您的 IDE 可能会为您做或要求它。
第一个文件:
package x;
public class MyMathMethods {
public boolean isPrime(int number) {
//your code here
return false;
}
}
第二:
package y;
import x.* //importing all files from the package x
//if your class MyMathMethods is in the same package, you don't need that
public class MainFile {
public static void main(String [] args) {
int number = 20;
boolean isNumberPrime;
MyMathMethods methods = new MyMathMethods();
isNumberPrime = methods.isPrime(number); //here the result if it's prime
}
}
编辑:我会尝试修复您的代码。
如果你想让你的方法静态,你可以调用它:
MyMathMethods.isPrime(numer);
无需创建新实例。
下一个问题:为什么要向函数传递一个未初始化的变量 (num) 并尝试从该方法的输入中获取该值? 嗯,这不是一个好习惯。 我宁愿建议从 main 中获取用户的输入(直接在 main 中在 main 中调用的另一个函数中),然后将值传递给 isPrime()。
package y;
import x.*
public class MainFile {
public static void main(String [] args) {
int num;
Scanner s = new Scanner(System.in);
num =s.nextInt();
if(MyMathMethods.isPrime(num)) {
//if true, your code;
} else {
//false, your code;
}
}
}
package x;
public class MyMathMethod {
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i < Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
您的算法对许多数字都失败了,例如 0、1、2。好吧,对于这个值,它甚至没有返回任何值。 请始终保护您的方法免受任何可能的错误参数的影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.