【问题标题】:Count numbers below 10 and print each one数出 10 以下的数字并打印出来
【发布时间】:2014-02-13 15:47:56
【问题描述】:

代码如下。

我想输入一些数字,测试每个数字是否低于 10,打印出低于 10 的总金额并打印出每个数字。

如何从循环中提取数字并在循环结束时打印出来?

如果我输入4,2,11,12并且循环结束,我如何打印出42

不使用数组。我是编程新手,还没有接触过数组。

谢谢

class Numbers
{
    public static boolean isNum(int num)
    {
        boolean returnValue;

        returnValue = false;

        if(num >= 0 && num < 10)
        {
            returnValue = true;
        }
        return returnValue;
    }

    public static void main (String [] args)
    {   
        int input; //numbers entered by user
        int numCount = 0; //numbers less than 10
        int index;
        boolean result;

        System.out.print("How many numbers to test? ");
        input = EasyIn.getInt();
        result = isNum(input);

        for(index = 0; index <= input; index++ )
        {
            System.out.println("Enter a number ");
            input = EasyIn.getInt();
            if(result == true)
            {
                numCount++;
            }
        }

        System.out.println("Total numbers below 10 is " + numCount);    

    }
}

【问题讨论】:

  • 是否必须等到循环结束才能打印数字?
  • @Thomas 是的,循环结束后,打印出有效数字

标签: java loops methods


【解决方案1】:

如果您绝对必须等到循环完成打印出您的数字,并且无法使用数组,您总是可以创建一个字符串并继续将您的有效数字附加到它(也许逗号分隔)。然后在循环完成后打印出这个字符串。

例如:

String output = "";
for (index = 0; index <= input; index++)
    input = EasyIn.getInt();
    result = isNum(input);

    if(result == true)
    {
        numCount++;
        output += input.ToString() + ", "; // you will probably want to remove the last comma
    }
}

output = output.replaceAll(", $", ""); // remove last comma
System.out.println("Total numbers below 10 is " + numCount); 
System.out.println("The numbers below 10: " + output)

【讨论】:

    【解决方案2】:

    由于您不能使用数组,并且假设其他集合也不存在问题,因此您唯一的选择是在获得十以下的数字时打印它们。您还需要更改代码以在每个输入的循环内调用result = isNum(input);,而不仅仅是您获得的第一个数字:

    input = EasyIn.getInt();
    result = isNum(input);
    if(result) // == true is implied
    {
        numCount++;
        System.out.println("Number under ten: "+input);
    }
    

    关于编码风格的说明:不要将booleantruefalse 进行比较。 另一个注意事项:返回布尔表达式的结果而不将它们分配给变量或if 语句是可以的。这整个代码块

    boolean returnValue;
    returnValue = false;
    if(num >= 0 && num < 10)
    {
        returnValue = true;
    }
    return returnValue;
    

    等价于

    return num >= 0 && num < 10;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-04
      • 2018-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-12
      • 2021-01-06
      相关资源
      最近更新 更多