如何在Java方法中使用while循环并打印添加函数?

时间:2011-06-12 00:27:40

标签: java string loops

我在上一个println中遇到了问题。我希望它打印上一个字符串打印的次数并将所有数字加在一起。因此,如果用户输入“3”,它将打印三次,然后将三个数字加在一起得到六个。 有谁知道我怎么做到这一点?或者我做错了什么?

    import java.util.Scanner;

    public class LoveCS { 
        public static void main(String[] args) { 
            int limit; 
            Scanner scan = new Scanner(System.in);
            System.out.println("How many times should the string be printed? " );
            limit = scan.nextInt();  
            int count = 1; 
            while (count <= limit){ 
                System.out.println(+count+"I love hot chocolate!!"); 
                count++;    
            } 
            sum+=limit;
            System.out.println("Java printed this message: "+ limit+ " times." + "The sum of the numbers from 1 to " + (count-1) + " is " sum);

        } 
    } 

3 个答案:

答案 0 :(得分:0)

您添加到总和的位置在循环之外,因此您只能获得最后一位。如果你将它移动到循环中,它应该工作。无论如何,你在哪里宣布总和?

答案 1 :(得分:0)

import java.util.Scanner;

public class LoveCS {

    public static void main(String[] args) {
        int limit;
        Scanner scan = new Scanner(System.in);
        System.out.println("How many times should the string be printed? ");
        limit = scan.nextInt();
        int count = 1;
        int sum = 0;
        while (count <= limit) {
            sum += count;
            System.out.println("I love hot chocolate!!");
            count++;
        }
        System.out.println("Java printed this message: " + limit + " times." + "The sum of the numbers from 1 to " + (count - 1) + " is " + sum);
     }
}

答案 2 :(得分:0)

而不是while循环:

int count = 1;
while (count <= limit) {
    // code inside loop
    count++;
}

使用for循环更简洁:

for (int count = 1; count <= limit, count++) {
    // code inside loop
}

它的代码更少,并且显而易见的是控制循环=更少的错误。

使用此将意味着更改到最后一行:

..."The sum of the numbers from 1 to " + limit + " is"... // change (count - 1) to limit