开发者

How do I use a while loop and print an addition function in Java Method?

开发者 https://www.devze.com 2023-03-12 20:53 出处:网络
I am having an issue in the last println. I want it to print the number of times the previous string was printed and add all the numbers together. So if the user entered \"3\" it would print it out th

I am having an issue in the last println. I want it to print the number of times the previous string was printed and add all the numbers together. So if the user entered "3" it would print it out three times then add the three numbers together to get six. Does anyone know how I can do that? Or what I'm doing wrong?

    import java.util.Scanner;

    public class LoveCS { 
        public static void main(String[] args) { 
            int limit; 
            Scanner scan = new S开发者_开发问答canner(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);

        } 
    } 


The place where you add to the sum is outside of the loop, so you'll only get the last bit. If you move it into the loop, it should work. Where are you declaring sum, anyway?


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);
     }
}


Instead of a while loop:

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

It's cleaner to use a for loop:

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

It's less code and it makes it obvious what is controlling the loop = less bugs.

Using this will mean a change to the last line:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号