當用戶輸入什麼是你應該做的是把你的計數邏輯死循環裏面,然後打破這個循環的等於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();
}
你已經說過你想要做什麼。你只需要在代碼中表達它。這裏有一個重播:**如果按下**零,你想** break **退出循環。 – Makoto
我已經試過,它打印Gemiddelde是NaN –
[「有人可以幫我嗎?」不是一個問題](http://meta.stackoverflow.com/q/284236)。請[編輯]你的問題,以更具體地瞭解你需要什麼。 –