所以我写了这个简单的应用程序。现在我想要做的是在按下 0 键时打印平均结果。当我将String值作为“getal”时,会打印出平均结果。
有人能指出我正确的方向吗?您可以在下面看到代码:
double i;
double getal = 0;
int tellen = 0;
while(input.hasNextDouble()) {
System.out.println("Volgenge getal");
i = input.nextDouble();
getal = getal + i;
tellen++;
}
System.out.println("Gemiddelde is " + getal / (tellen));
答案 0 :(得分:1)
你应该做的是将你的计数逻辑放在一个无限循环中,然后在用户输入等于0时突破该循环:
double i;
double getal = 0;
int tellen = 0;
Scanner input = new Scanner(System.in);
while(true) {
System.out.println("Volgenge getal");
i = input.nextDouble();
getal = getal + i;
if(i == 0){
//break statements end the loop
break;
}
//we need to increment our count down here so the '0' doesnt count
tellen++;
}
System.out.println("Gemiddelde is " + getal / (tellen));
input.close();
}
还有许多其他方法可以做到这一点,它不必与我使用的确切逻辑一致。以下是使用do while
循环执行此操作的另一种方法。
double i;
double getal = 0;
//in this example we need to start the count at -1 since we are going to be counting the '0'
int tellen = -1;
Scanner input = new Scanner(System.in);
do{
System.out.println("Volgenge getal");
i = input.nextDouble();
getal = getal + i;
//we need to increment our count down here so the '0' doesnt count
tellen++;
}while(i != 0);
System.out.println("Gemiddelde is " + getal / (tellen));
input.close();
}