问题描述
|
我在上一个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