仅供参考:我是初学者。另外,我知道调用方法是一个新手概念,并且已经有一些这样的线程。我的情况有点不同,因为我非常受伪代码的限制,我的程序必须相同地镜像。我无法从其他方法调用方法,包括从 main 内部调用方法。这是伪代码,后面是我编写的代码:
伪代码:
// The user enters an integer and the program calculates that many primes
// It uses 3 methods, including the main. All the methods are in the same class
// and should be declared as ‘public static.’
Project Print the First n Primes
Package printTheFirstNPrimesPackage
Class PrintTheFirstNPrimes
Method Main
Declare numberOfPrimes as integer
Print “How many prime numbers do you want?"
Read numberOfPrimes from the keyboard
Call the method: PrintNPrimes(numberOfPrimes)
end Method (Main)
// ***********************************************************
// This method accepts an integer and prints that many prime
// numbers, starting at 2. 2 is the lowest primt number.
// ***********************************************************
Method void PrintNPrimes(int n)
declare i as integer
declare myNum as integer
myNum = 2 // The first prime number
i = 0
loop while i < n // This could be a ‘for’ loop
if IsPrime(myNum) // Call the Isprime method, (see below)
i = i + 1
print myNum
End If
myNum = myNum + 1
end loop
end Method PrintNPrimes
// **********************************************************
// This method accepts an integer and tests to see if it is
// a prime number. If it is prime, the method returns true,
// otherwise it returns false.
// **********************************************************
Method boolean IsPrime(int number)
Declare result as boolean
result = true
declare i as integer
i = 2
loop while i < number
if ((number % i) == 0)
result = false
exit loop
end if
end loop
return result
end Method
end Class
End Package
End Project
JAVA代码:
package printTheFirstNPrimesPackage;
import java.util.*;
public class PrintTheFirstNPrimes {
public static void main(String [] args) {
int numberOfPrimes;
Scanner primes = new Scanner(System.in);
System.out.println("How many prime numbers do you want?");
numberOfPrimes = primes.nextInt();
// Call the method PrintNPrimes(numberOfPrimes)
}
public static void PrintNPrimes(int n) {
int i;
int myNum;
myNum = 2; // The first prime number
i = 0; {
while (i < n)
// if IsPrime(myNum) // Call the IsPrime method (see below) {
i = i + 1;
System.out.println(myNum);
myNum = myNum + 1;
}
}
public static boolean IsPrime(int number) {
boolean result;
result = true;
int i = 2;
while (i < number) {
if ((number % 1) == 0)
result = false;
}
return result;
}
}
我的主要问题是在 if 语句中调用 IsPrime 方法。我收到一条错误消息,说 IsPrime 无法从我知道的 int 转换为 boolean,但伪代码限制了我做很多其他事情。我还想就如何在方法 main 中调用 PrintNPrimes 方法提出建议。谢谢。