Java中的快乐或不快乐数字,无法正常工作

时间:2014-02-09 21:17:53

标签: java

出于某种原因,这不起作用,我无法弄清楚原因。即使它是假的,它也只返回true,其他一切似乎都有效,除非它不会返回false。请帮忙!我是Java编程的新手,非常感谢有人发现我的错误!

import javax.swing.JOptionPane;

public class A2Q1 {

    public static void main(String[] args) {
        int number, input1, min, max;
        String input;
        boolean trueFalse;

        //constants
        min = 0;
        max = 1000000;

        input = JOptionPane.showInputDialog(null, "Input number -1 to quit");
        input1 = Integer.parseInt(input);

        while (input1 != -1) {
            number = getNumber(min, max); // gets the number the user wants to test
            trueFalse = isHappy(number); //tests if the number is happy or unhappy

            //getting the returned value and telling the user if it is happy or unhappy
            if (false) {
                System.out.println(number + " is unhappy");
            } else {
                System.out.println(number + " is happy");
            }

            //getting input from the user to continue to quit
            input = JOptionPane.showInputDialog(null, input number - 1 to quit"); 
            input1 = Integer.parseInt(input);
        }
        System.out.println("End of Processing");
    }

    public static int getNumber(int min, int max) //get the number from the user 
    {
        //declaring variables 
        String input;
        int number;
        //getting input from the user for the value they want to test
        input = JOptionPane.showInputDialog(null, 
        "What is the value you 

        number = Integer.parseInt(input);

        if (number > 0 && number < 100000) {
            return number;
        } else {
            System.out.println("You have entered an invalid number");
            return number;
        }
    } //closing getNumber

    public static boolean isHappy(int number) {
        //declaring variables
        int digit1, digit2, digit3, sum;

        while (number != 0 && number != 1 && number != 4 && number != 16 && number != 20
                && number != 37 && number != 42 && number != 58 && number != 89 && number != 145) {
            digit1 = number % 1000;
            digit1 = digit1 / 100;
            digit2 = number % 100;
            digit2 = digit2 / 10;
            digit3 = number % 10;
            digit1 *= digit1;
            digit2 *= digit2;
            digit3 *= digit3;
            number = digit1 + digit2 + digit3;
        }

        if (number == 1) {
            return true;
        } else {
            return false;
        }

    } //closing isHappy 
}//closing public class

1 个答案:

答案 0 :(得分:2)

你的问题就在这里。

  trueFalse = isHappy(number); //tests if the number is happy or unhappy

  //getting the returned value and telling the user if it is happy or unhappy
  if (false)
  {
    System.out.println(number + " is unhappy");
  }
  else
  {
    System.out.println(number + " is happy");
  }   

条件if(false)永远不会成立。你希望它改为if(trueFalse),并绕过“true”分支和它下面的“false”分支。