【问题标题】:Adding numbers 1 to n with a loop使用循环将数字 1 添加到 n
【发布时间】:2018-06-11 21:13:02
【问题描述】:

所以发布的代码有效并且似乎给出了正确的值。唯一的问题是它打印循环中的每一行,而不仅仅是答案。我怎样才能让它只打印答案而不是每行导致它?

import java.util.Scanner;
public class CountLoop{
public static void main (String[] args){
    Scanner in = new Scanner (System.in);
    int i = -1;
    int limit = 0;
    System.out.println("Please enter a number");
    String end1 = in.nextLine();
    int end = Integer.parseInt(end1);


    while (i < end){
        i++;
        limit = (i + limit);
        System.out.println("The sum of the numbers in between 0 and " + end + " is i = " + limit);

    }
}

}

我也可以使用其他类型的循环,因为我需要展示一个示例,其中包含所有不同类型的循环,因此我们不胜感激。

【问题讨论】:

    标签: java loops while-loop integer break


    【解决方案1】:

    将您的 system.out.println 移出您的 while 循环

    while (i < end){
        i++;
        limit = (i + limit);
    }
    
    System.out.println("The sum of the numbers in between 0 and " + end + " is i = " + limit);
    

    【讨论】:

    • 这样一个简单的解决方案,但一个有效的答案。谢谢!
    【解决方案2】:

    或者 Java 8 中的现代版本:

    int sum = IntStream.range(startInclusive,endExclusive).sum(); 
    
    System.out.println("The sum of the numbers in between " + startInclusive +
                       " and " + (endExclusive -1) + " is sum = " + sum);
    

    重命名变量;-)

    限制->总和
    0 -> 开始包容
    end -> endExclusive - 1

    【讨论】:

      猜你喜欢
      • 2014-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-30
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      相关资源
      最近更新 更多