现在如何添加显示的数字并打印出来? 我得到了如何显示它们,但无法弄清楚如何添加数字,请对我的项目有很大的帮助
import java.util.Scanner;
public class ReadNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Number: \n");
int n = sc.nextInt();
int i = 0;
while(i <= n){
System.out.print(i);
if(i == n){
System.out.print("=");
}
else{
System.out.print("+");
}
i++;
}
}
}
答案 0 :(得分:1)
您需要运行总计的另一个变量。为了更简洁,请使用for
循环,并处理循环外的i == n
。
Scanner sc = new Scanner(System.in);
System.out.println("Enter Number: \n");
int n = sc.nextInt();
int i = 0, sum = n;
for (int i = 0; i < n; i++) {
sum += i;
System.out.print(i + "+");
}
System.out.println(n + "=" + sum);
答案 1 :(得分:0)
您可以创建另一个变量int sum
,以便在每次循环迭代时更新所有i
的总和:
import java.util.Scanner;
public class ReadNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Number: \n");
int n = sc.nextInt();
int i = 0;
int sum = 0; // Create a sum variable
while(i <= n){
System.out.print(i);
sum+=i; // Add `i` to sum
if(i == n){
System.out.print("=");
System.out.println(sum); // Display `sum` after loops finish
}
else{
System.out.print("+");
}
i++;
}
}
}