当我使用我的代码时,我收到一条输出消息,指出我输入的每个号码都是素数,即使它不是素数。如何更改输出消息以反映正确的或不是主要结果?这是我的代码:
public static void main (String [] args){
//prompt user to input a number
String input = JOptionPane.showInputDialog("Enter number ");
// change string to int
int number = Integer.parseInt(input);
//display message to user of their results
BigInteger num = new BigInteger(input);
String output = number + " is" + (BigInteger(input) ? " " : " not ") + "a prime number: " + BigInteger(input);
JOptionPane.showMessageDialog (null, output);
}
public static Boolean IsPrime(BigInteger num) {
// check if number is a multiple of 2
if (num.mod(new BigInteger("2")).compareTo(BigInteger.ZERO) == 0) {
return false;
}// if not, then just check the odds
for (BigInteger i = new BigInteger("3"); i.multiply(i).compareTo(num) <= 0; i =
i.add(new BigInteger("2"))) {
if (num.mod(i).compareTo(BigInteger.ZERO) == 0) {
return false;
}
}
return true;
}
答案 0 :(得分:1)
我认为你在这里有问题 -
String output = number + " is"
+ (BigInteger(input) ? " " : " not ") + "a prime number: "
+ BigInteger(input);
你想要更像这样的东西 -
String output = num + " is"
+ (IsPrime(num) ? " " : " not ") + "a prime number.";
我测试了你的IsPrime
函数,它正确识别出5为素数,4为非素数。您应该将其重命名为isPrime
以符合Java命名约定。
修改强>
public static void main(String[] args) {
// prompt user to input a number
String input = JOptionPane.showInputDialog("Enter number ");
// change string to int
int number = Integer.parseInt(input);
// display message to user of their results
BigInteger num = new BigInteger(input);
String output = num + " is" + (IsPrime(num) ? " " : " not ")
+ "a prime number.";
JOptionPane.showMessageDialog(null, output);
}
答案 1 :(得分:0)
我猜你在主代码中错了;试试这个;
public static void main (String [] args){
//prompt user to input a number
String input = JOptionPane.showInputDialog("Enter number ");
// change string to int
int number = Integer.parseInt(input);
//display message to user of their results
BigInteger num = new BigInteger(input);
String output = number + " is" + (IsPrime(num) ? " " : " not ") + "a prime number: " + number;
JOptionPane.showMessageDialog (null, output);
}
安吉洛