关于java while循环和检查器的问题

时间:2015-04-16 06:03:42

标签: java

我正在编写一个允许用户输入数字的Java程序,然后该程序将5,8和9组合起来以获取用户的输入数字。

我想获得以下样本:

1

  

你找到这个组合的号码是什么?

     

8

     

你的号码有1个

2

  

你找到这个组合的号码是什么?

     

13

     

你的号码有1个5和1个

3

  

你找到这个组合的号码是什么?

     

11

     

无效号码

以下是我写的代码:

import java.util.Scanner;
class combine {
    public static void main (String[] args){
        System.out.println("what is your number that you what to find the combination? ");
        Scanner scan = new Scanner(System.in);
        if (num < 5){
            System.out.println("invalid number");
            System.exit(0);
        }
//Begin Looping
        for (int g=0; g<=1000000;g++){
//Find the the number left after minus g*5
            int left = num - g*5;
//Check the combination of 5 and 8
            if (left%8 == 0){
                System.out.format("your number has %d fives and %d eights\n",g,left/8);
                System.exit(0);
            }
//Check the combination of 5 and 9
            if (left%9 == 0){
                System.out.format("your number has %d fives and %d nines\n",g,left/9);
                System.exit(0);
            }
//Check the combination of 8 and 9
            while (false){     //This while loop doesn't work. It fails compile.
                int left2 = nuggets_num - g*8;
                try{
                    if (left%8 == 0){
                            System.out.format("your number has %d eights and %d nines\n",g,left/8);
                            System.exit(0);
                    }
                    if (left%8 != 0){
                        System.out.println("invalid number");
                    }
                }
            }
        }
        System.out.println("invalid number");
    }
}
//I am a beginner and I know that reading my codes might be painful, sorry about that:(

正如我所提到的,我的while循环不起作用。所以我的程序找不到&#34; 17&#34;的组合,应该是1 8和1 9。如何解决?

另外,我的节目输出不够干净。例如,如果用户输入&#34; 8&#34;,我的程序将输出&#34;您的号码有0五和一个8&#34;。如何添加检查器以避免这些情况?喜欢输出&#34;你的号码有1个星期四&#34;而不是前一个输出。

2 个答案:

答案 0 :(得分:1)

您正在使用while(false),这意味着永远不会执行此循环。 Java编译器足够智能,可以阻止你编译知道不会运行的东西。

至于你的逻辑,当你从某个数字中扣除5的最大倍数(这意味着你的模数是5)时,余数永远不会超过4!所以,你应该做以下的事情:

  1. 将输入除以9.这将为您提供该输入中9的计数。
  2. 将输入数量乘以9.这将给出余数,它将小于或等于8.
  3. 分别用8和5执行步骤1和2。
  4. 使用上述算法的输出格式化输出字符串。

答案 1 :(得分:0)

你对除法和模数运算符有一个基本的误解。 你试图将一个数字除以一个特定的数字来“摆脱”它,但这只适用于你乘以10的乘法(假设你在十进制系统中工作)。

例如,(1985 / 10) = 198,但888 / 8不等于88

%运算符也一样 - (350 % 3)不会返回50!它实际上等于2

相关问题