当用户输入什么是你应该做的是把你的计数逻辑死循环里面,然后打破这个循环的等于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)。请[编辑]你的问题,以更具体地了解你需要什么。 –