Semplice query java - ottenendo un risultato da un numero intero
-
27-10-2019 - |
Domanda
Sono stato impostato un incarico in cui devo trovare la media di un elenco di numeri positivi enterd dall'utente, la quantità di numeri immessi è sconosciuta. Finora ho ottenuto il programma per aggiungere tutti i numeri che sono stati inseriti (la voce teminate quando un utente inserisce 0). Non voglio la risposta a questa domanda qui perché sto davvero cercando di imparare così velocemente!
Ho problemi con la dichiarazione di tempo,
volevo dire
WHILE ( numberentered = 0 );
......
Ma questo non sembra funzionare
Inizialmente l'ho fatto così:
while ( numberentered >= 1 );
System.out.print (numbersum);
Ma questo salta ancora fuori dal loop quando viene inserito un numero negativo.
Qualche idea ragazzi ... se capisci la mia domanda ma è ancora molto male ... per favore modifica.
Grazie.
Soluzione
Non dovresti farlo?
while(numberEntered != 0) {
// add it up
}
Altri suggerimenti
while (numberentered != 0) { < read new number and add it to total and ... (but you didn't want the answer...) > }
It seems like maybe you meant to do:
while (numberentered != 0) {
//do stuff
}
Note that no semicolon is needed on the 'while' line itself.
This is what I interpreted the problem statement:
"User is allowed to enter the numbers as many times but when it enters 0, the program would display the average of the numbers being entered prior to 0 and exit"
You may go this way:
public static void main(String args[]) {
float no = 0;
float average = 0;
int count = 1;
if(args.length == 0) {
printf("No number being entered...program exits");
System.exit(0);
}
if(args[0] == 0) {
displayAverage(average);
return;
}
for(count;count<args.length;count++){
try {
no = Float.parseFloat(args[count]);
if(no == 0 ) {
break;
}
average = average + no;
}
catch(NumberFormatException nfe) {
printf("Please enter only numbers");
}
}
average = average/count;
printAverage(average);
}
private void displayAverage(float average){
System.out.println("average is: "+ average);
}
hope this may helps..