【问题标题】:how to output answer after each input using a loop?如何使用循环在每次输入后输出答案?
【发布时间】:2017-02-07 17:15:04
【问题描述】:

如果我想输入 10 个数字,并且在每个数字之后显示平方根,我将如何使用 for 循环来做到这一点?

int number; 
System.out.print("Enter a number: ");
num = input.nextInt();
for (count = 0; count <= 10; count++)
{
    System.out.println("The Square of Number is : "+(num*num));
    System.out.println("The Cube of Number is : "+(num*num*num));

我已经尝试过这段代码。但是,它显示 1 个输入 10 次。如何在每次输入后显示它?

【问题讨论】:

  • num = input.nextInt(); 将其移入for

标签: java loops for-loop foreach


【解决方案1】:

与其他人所说的类似,您只需输入一次,然后打印输出 10 次。 input.nextInt() 必须移到 for 循环内。

但是,尚未说明的是您没有使用换行分隔符。 (假设您使用的是控制台,您似乎就是这样)当用户通过按回车键输入文本时,输入末尾有一个换行符分隔符。您只使用数字,而不是换行符。

可以在here.找到一个例子

【讨论】:

    【解决方案2】:

    如果您想在输入数字后输出平方根,只需将 num = input.nextInt(); 放入 for 循环中,如前所述。

    如果你想先输入 10 个数字,然后输出每个数字的平方,这将是一个很好的解决方案:

    int[] numbers = new int[10];
    for(int i = 0; i < numbers.length; i++) numbers[i] = input.nextInt();
    for(int tempInt : numbers) System.out.println(Math.pow(tempInt, 2));
    

    【讨论】:

      【解决方案3】:

      像@Pavneet Singh 所说,将num = input.nextInt() 移动到for loop 中。如果您希望它在输入后显示全部 10,请使用长度为 10 的 int[],如下所示:

      int[] numbers = new int[10];
      

      【讨论】:

        猜你喜欢
        • 2021-12-20
        • 2022-01-21
        • 1970-01-01
        • 1970-01-01
        • 2015-07-08
        • 2017-01-06
        • 1970-01-01
        • 2022-01-07
        • 2020-03-30
        相关资源
        最近更新 更多