![](/img/trans.png)
[英]How can I create a scanner with array and also find min ,max and average of input user in java?
[英]How can I get the min and max value of the user input? (Java)
我是Java的新手,我正在尝试编写一个程序来询问用户:
public class ExtraClase {
public static void main(String[] args) {
Estudiantes estudiantes = new Estudiantes();
estudiantes.numeroEstudiantes();
}
}
public class Estudiantes {
public void numeroEstudiantes() {
System.out.print("Introduzca numero de estudiantes: ");
Scanner cantidad = new Scanner(System.in);
int number = cantidad.nextInt();
int i=1;
int total=0;
int promedio;
if(number>=1 && number<=35){
while(i<=number){
System.out.print("Ingrese la nota del 1-100: ");
Scanner nota = new Scanner(System.in);
int note = nota.nextInt();
if(note>=1 && note<=100) {
}else {
//como elimino la ultima nota introducida
System.out.println("Ingrese valor entre 1 y 100.");
number++;
}
total=total+note;
i++;
}
}else {
System.out.println("Digite numero entre 1 y 35.");
}
promedio=total/number;
System.out.println("El promedio de notas es: "+promedio);
System.out.println("La nota mas alta es: ");
System.out.println("La nota mas baja es: ");
}
}
if(note>=1 && note<=100) {
total=total+note;
i++;
}else {
//como elimino la ultima nota introducida
System.out.println("Ingrese valor entre 1 y 100.");
//there's no need to increment number here, just don't increment i if a variable has invalid value
}
2:您将在检查是否有效的if
语句之外增加总数。 因此,不会将您的无效值200排除在外。
3:您需要在单独的变量中跟踪最大值和最小值。
您需要移动这些行以添加总计,并将i
递增到if(note>=1 && note<=100)
的第一部分。 您还可以通过添加另外两个变量来跟踪最大/最小:
public class Estudiantes {
public void numeroEstudiantes() {
System.out.print("Introduzca numero de estudiantes: ");
Scanner cantidad = new Scanner(System.in);
int number = cantidad.nextInt();
int i=1;
int total=0;
//added min/max
int baja=-1;
int alta=-1;
int promedio;
if(number>=1 && number<=35){
while(i<=number){
System.out.print("Ingrese la nota del 1-100: ");
Scanner nota = new Scanner(System.in);
int note = nota.nextInt();
if(note>=1 && note<=100) {
//check for min
if(note<baja || baja==-1){
baja = note;
}
//check for max
if(note>alta || alta==-1){
alta = note;
}
//moved from below
total=total+note;
i++;
} else {
//como elimino la ultima nota introducida
System.out.println("Ingrese valor entre 1 y 100.");
number++;
}
}
} else {
System.out.println("Digite numero entre 1 y 35.");
}
promedio=total/number;
System.out.println("El promedio de notas es: "+promedio);
System.out.println("La nota mas alta es: " + alta);
System.out.println("La nota mas baja es: " + baja);
}
}
再创建2个变量
//for your case if value is between 0 and 100
int min = 101;
int max = 0;
if(note>=1 && note<=100) {
total=total+note;
i++;
//checking minimum value
if(note < min)
min = note;
//checking maximum value
if(note > max)
max = note;
}else {
System.out.println("Enter integer between 1 and 100");
//not valid no.
}
最后打印最小和最大变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.