字符串输出以向用户显示消息

时间:2014-04-16 18:38:38

标签: java string user-interface boolean biginteger

当我使用我的代码时,我收到一条输出消息,指出我输入的每个号码都是素数,即使它不是素数。如何更改输出消息以反映正确的或不是主要结果?这是我的代码:

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;

}

2 个答案:

答案 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);
}

First prompt

Not Prime

Is Prime

答案 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);
    }

安吉洛