作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我希望我的代码循环,但将变量重新初始化回 0。每次我输入一个数字时,它都会将其添加到之前的结果中,但我希望它重置。我在下面附上了两张图片。一个是实际输出,另一个是期望输出。
import java.util.Scanner;
public class AddOrMultiplyNNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String am;
int sum = 0;
int total = 1;
int n = 0;
while (true) {
System.out.print("enter an integer number: ");
n = input.nextInt();
if(n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
am = input.nextLine();
if (am.equals("a")) {
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
}
}
实际输出
期望的输出
最佳答案
您可以使用继续
if(n == 0) {
sum = 0;
total = 1;
continue;
}
关于java - 如何在java中的while循环中将变量初始化回0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54432606/
我是一名优秀的程序员,十分优秀!