How to create string vectors in java?

Asked

Viewed 9,847 times

5

"Make an algorithm to receive an integer n (number of students), an integer m (number of subjects), and nxm grades from 0 to 10, which each student obtained in each discipline. Present:

a) which (or which) subject(s) the students scored the highest average
b) which (or which) course(s) the students got the lowest average grade
c) which (or which) student(s) had the highest overall average d) which (or which) student(s) got the lowest overall average"

I thought I’d create a string for the students' names, another for the disciplines, and then create the matrix with the grades. Only then would I think of a way to calculate the average. From what I understand, I must print on the screen the names of the disciplines that correspond to the higher and lower averages; the same goes for the students. But I am unable to create such strings...

    public static void main(String[] args) {
        Scanner ent = new Scanner(System.in);
        ent.useLocale(Locale.US);
        int n, m, i, j;;
        n = ent.nextInt(); // numero de alunos
        m = ent.nextInt(); // numero de disciplinas            
        String [] a = new String[n]; // nomes dos alunos
        String [] d = new String[m]; // nomes das disciplinas
        double [][] M = new double[n][m]; // notas
        // nomes dos alunos
        for (i=0; i<n; i++) {
            a[i] = ent.nextLine();
        }
        // nomes das disciplinas
        for (j=0; j<m; j++) {
            d[i] = ent.nextLine();
        }
        // monta tabela de notas: alunos X disciplinas
        for (i=0; i<n; i++) {
            for (j=0; j<m; j++) {
                M[i][j] = ent.nextDouble();
            }            
        }
        // calcula a nota média de cada disciplina
        double soma=0, media=0;
        for (j=0; j<m; j++) {
            for (i=0; i<n; i++) {
                soma = soma + M[i][j];
            }
            media = soma/n;
            System.out.println("Média de "+d[j]+": "+media);
        }
    }

When I run the program and type the name of the first student or type all and then enter, the following message appears:

Exception in thread "main" java.util.Inputmismatchexception at
java.util.Scanner.throwFor(Scanner.java:909) at
java.util.Scanner.next(Scanner.java:1530) at
java.util.Scanner.nextInt(Scanner.java:2160) at
java.util.Scanner.nextInt(Scanner.java:2119) at
aula11.teste.main(test.java:8) Java Result: 1

I don’t know what you mean or what I should do to make it right.

  • Because the ent.useLocale(Locale.US);?

  • Because I use dot to separate decimals. Using comma gives error.

  • I still don’t know what the problem is with the Scanner, but in calculating the average you will need to put soma = 0; at the beginning of for that iterates the j in the end, but before the forintern.

  • Or else move the declaration of the soma and of media to the beginning of for that is just below.

  • What is line 8 in your program? It reads the n?

  • Okay, I’ll arrange that, thanks for the tip. For now my problem is creating the strings, otherwise I have no way to display the names of students and subjects of higher and lower average.

  • Yes, line 8 reads n.

Show 3 more comments

1 answer

10


First, note this part:

    for (j=0; j<m; j++) {
        d[i] = ent.nextLine();
    }

You iterate the variable j, but accesses the array using i. This is wrong. To avoid errors like this, it is recommended to declare the variable on itself for, thus:

    for (int j=0; j<m; j++) {
        d[j] = ent.nextLine();
    }

And then, you no longer have to declare i and j out of the loop. This has the advantage that if you use the wrong variable, the compiler is more likely to find the error for you.

Continuing back to your original problem, this is your line 8:

n = ent.nextInt(); // numero de alunos

That is, are you sure you actually typed an integer number, not a decimal number or the name of some student or discipline?

To avoid these kinds of problems, I recommend putting this in the program, out of the method main, may be before or after:

private static int lerInt(String mensagem, Scanner scanner) {
    while (true) {
        System.out.println(mensagem);
        String lido = scanner.nextLine().trim();
        try {
            return Integer.parseInt(lido);
        } catch (NumberFormatException e) {
            System.out.println("Desculpe, mas " + lido + " não é um número inteiro. Tente novamente.");
        }
    }
}

private static double lerDouble(String mensagem, Scanner scanner) {
    while (true) {
        System.out.println(mensagem);
        String lido = scanner.nextLine().trim();
        try {
            return Double.parseDouble(lido);
        } catch (NumberFormatException e) {
            System.out.println("Desculpe, mas " + lido + " não é um número real. Tente novamente.");
        }
    }
}

private static String lerString(String mensagem, Scanner scanner) {
    while (true) {
        System.out.println(mensagem);
        String lido = scanner.nextLine().trim();
        if (!lido.isEmpty()) return lido;
        System.out.println("Desculpe, você não digitou nada. Tente novamente.");
    }
}

And then you use them this way:

int n = lerInt("Digite o numero de alunos", ent);
int m = lerInt("Digite o numero de disciplinas", ent);

...

// nomes dos alunos
for (int i=0; i<n; i++) {
    a[i] = lerString("Digite o nome do " + (i + 1) + "o aluno.", ent);
}
// nomes das disciplinas
for (int j=0; j<n; j++) {
    d[j] = lerString("Digite o nome da " + (j + 1) + "a disciplina.", ent);
}

...

for (int i=0; i<n; i++) {
    for (int j=0; j<m; j++) {
        M[i][j] = lerDouble("Digite a nota de " + d[j] + " do aluno " + a[i] + ".", ent);
    }
}

And you can erase these lines:

    ent.useLocale(Locale.US);
    int n, m, i, j;;

There is also a little problem in your average calculation. Instead:

    double soma=0, media=0;
    for (j=0; j<m; j++) {
        for (i=0; i<n; i++) {

Use this:

    for (int j=0; j<m; j++) {
        double soma=0, media;
        for (int i=0; i<n; i++) {

The reason is that the sum has to go back to zero when you change discipline.

  • 1

    Boy, I’ve messed up a lot of stupid things! I spend so much time trying to solve a problem that when I go to the next problem I do everything wrong. Thanks for your help!

  • 1

    I managed to make everything work right! It was different from what you suggested (I did it in a less practical way), but your tips helped A lot. Thank you very much!!

Browser other questions tagged

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