Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        4年前关闭。
                                                                                            
                
        
我对Java不熟悉,所以对不起,这是一个简单的问题。

我总是觉得很有趣,您可以通过将数字加在一起将数字压缩为一个数字。因此,我决定尝试编写一个程序为我做!这是一个例子。


  输入:557
  
  5 + 5 + 7 = 17
  
  1 + 7 = 8
  
  答:8


看到!这显然适用于任何数量。但是,我的程序正在终止,没有任何输出。谁能帮我吗?我不太习惯tringBuilder,所以我认为这可能是问题所在。

import java.util.Scanner;
import java.lang.StringBuilder;

public class MagicNumberApp
{
    public static void main (String [] args)
    {
        int number;
        String numberstring;
        boolean keepGoing = false;

        Scanner input = new Scanner(System.in);
        StringBuilder builder = new StringBuilder();

        sopl("Welcome to Magic Number! \nThe idea is to add the idividual digits of a number "
                + "\nuntil it is condensed into a one digit number.\n\nInput a number...");
        sop(">");

        number = input.nextInt();

        numberstring = Integer.toString(number);

        if (numberstring.length() < 1)
            keepGoing = true;

        sopl("");

        number = 0;

        while (keepGoing)
        {
            for (int i = 0; i < numberstring.length(); i++)
            {
                number += Character.getNumericValue(numberstring.charAt(i));
                builder.append("+" + numberstring.charAt(i) + " ");
            }
            builder.append("=" + number);
            sopl(builder);

            if (numberstring.length() > 1)
            {
                numberstring = Integer.toString(number);
                number = 0;
                sopl("");
            }
            else
            {
                keepGoing = false;
            }
        }

    }

    public static void sop (Object o)
    {
        System.out.print(o);
    }

    public static void sopl (Object o)
    {
        System.out.println(o);
    }

}

最佳答案

您的keepGoing逻辑倒退了。您将keepGoing设置为true时,输入的数字小于1位,并将其初始化为false

if (numberstring.length() < 1)
    keepGoing = false;


所有数字都至少包含一位,甚至0,因此在while循环之前不需要进行上述测试。去掉它。但是您必须将keepGoing初始化为true

10-01 22:20