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

问题描述

| 我在上一个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);

        } 
    } 
    

解决方法

        您添加总和的位置不在循环之外,因此您只会得到最后一位。如果将其移动到循环中,它将正常工作。无论如何,您在哪里申报款项?     ,        
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);
     }
}
    ,        代替
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
    

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...