Array with dynamic ability and how to invalidate other characters in reading

Asked

Viewed 252 times

3

I did the code below but found 2 problems:

  • The value of the vector is set to 100 and must be the amount of numbers the user wants.
  • Another problem I found is that the statement specifies that there should be a validation if the user enters invalid values:

Invalid arguments should be disregarded (Print a message for each invalid value. ), without causing the display of exceptions (Display a message to the user asking him to re-enter the value).

import java.util.Scanner;

//falta tratar valores inválidos

public class Media {

    public static void main(String[] args) {
        //esse vetor não pode ter valor fixo, o usuário deve inserir quantos valores quiser, como fazer?
        float valor[] = new float[100], media = 0;
        int j = 0, i;

        Scanner scanner = new Scanner(System.in);

        System.out.println("Insira um valor: ");

        while (!scanner.hasNext("S")) {
            System.out.println("Insira um valor: ");
            valor[j] = scanner.nextFloat();
            j++;
        }
        for (i = 0; i < j; i++) {
            media += valor[i];
        }
        media = media/i;

        System.out.println("Média: "+ media);
    }
}
  • 1

    Using vectors, the only way is to start it after taking the size typed by the user, setting this value, something like int entrada = scanner.nextInt(); float valor[] = new float[entrada].

1 answer

4


Arrays have fixed size. When you need unknown size you need to use a ArrayList. I used it because it’s the question and I might use it somewhere else later, in the current way or array, nor ArrayList it is necessary:

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);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Simpler and starting to validate:

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);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

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 don’t know if it meets the requirement but I’d 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);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

In the next questions put a problem at a time and well defined. Have done this in the previous question harmed the answers, so what was posted there ended up not helping to solve the problem in fact, so much so that here is not using the solution presented there, even having accepted a response. This would happen here too.

I changed the code to a suitable solution. At least within what I understood the problem is not so clear. The path that was being adopted generated various confusions and waste.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.