[英]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.