Arrays have fixed size. When you need unknown size you need to use a ArrayList
. I used it because it's the question and it might be that I'll use it somewhere else later, in the current way neither array , nor ArrayList
is required:
import java.util.Scanner;
import java.util.ArrayList;
class Media {
public static void main(String[] args) {
ArrayList<Float> valores= new ArrayList<Float>();
float acumulador = 0;
int contador = 0;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Insira um valor: ");
float valor = scanner.nextFloat();
if (false) { //vai colocar a valisação aqui
System.out.println("Valor inválido digite um válido");
continue;
}
valores.add(valor);
contador++;
acumulador += valor;
System.out.println("Deseja inserir outro valor S/N? ");
if (!scanner.next().equals("S")) {
break;
}
}
for (int i = 0; i < valores.size(); i++) {
System.out.println("Nota " + (i + 1) + ": " + valores.get(i));
}
System.out.println("Média: "+ acumulador / contador);
}
}
See running on ideone .
Simpler and starting to do the validation:
import java.util.Scanner;
class Media {
public static void main(String[] args) {
float acumulador = 0;
int contador = 0;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Insira um valor: ");
float valor = scanner.nextFloat();
if (false) { //vai colocar a valisação aqui
System.out.println("Valor inválido digite um válido");
continue;
}
contador++;
acumulador += valor;
System.out.println("Deseja inserir outro valor S/N? ");
if (!scanner.next().equals("S")) {
break;
}
}
System.out.println("Média: "+ acumulador / contador);
}
}
See running on ideone .
I did not put the validation because the question does not describe how it should be validated, but the basic logic is present, just change the condition.
I do not know if it meets the requirement but I would do it differently:
import java.util.Scanner;
class Media {
public static void main(String[] args) {
float acumulador = 0;
int contador = 0;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Insira um valor: ");
String dado = scanner.nextLine();
if (dado.equals("N")) {
break;
}
try {
float valor = Float.parseFloat(dado);
contador++;
acumulador += valor;
} catch (NumberFormatException ex) {
System.out.println("Valor inválido digite um válido");
}
}
System.out.println("Média: "+ acumulador / contador);
}
}
See running ideone .
In the next questions put one problem at a time and well defined. Doing this on the previous question has crippled the answers, so what was posted there did not help solve the problem. fact that it is not using the solution presented here, even though I have accepted a response. This would happen here too.
I've changed the code to a proper solution. At least within what I understood the problem is not so clear. The path that was being adopted created a lot of confusion and waste.