Show typed string string

Asked

Viewed 301 times

1

How to show read values inside a repeat loop in Java? Ex:

for(int i = 1; i <= 2; i++){
     System.out.print("Nome: ");
     String nome = tecla.nextLine();
}

?? <- Make the read names appear here

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

1

You’ll have to wear one array (vector) so that a variable has several indexed memory positions. Have you apprehended matrix at school? It is basically a matrix with only one dimension.

Array index

So actually in this example we have 10 variables in memory that accessed by a name and an index and a variable that encompasses those variables that can be accessed by the name, but without an index you can’t access what’s inside it.

Brackets are used to indicate the index that will be accessed in this variable.

The array always starts with 0, so I changed your for.

Without the vector each repeat cycle of the for delete the value previously stored in the variable, so you have to reserve positions for all entries you want to enter, the array is the solution.

Of course, in a simple example like this you could have created 3 variables and not have a loop, but I imagine you want to do it the way you do it in real applications. If it were 100 it would just change the number there. Alias that is considered magic number, in real code, it is not good to do so. But actually in actual code, you will ask how many entries you have and allocate dynamically, or use a list instead of the array and keep adding while the person is typing new entries. But this leaves for next.

It can improve more this code, but we will not do everything at once.

import java.util.*;

class HelloWorld {
    public static void main (String[] args) {
        String[] nomes = new String[3]; //declara a variável e inicializa com 3 posições
        Scanner scanner = new Scanner(System.in);
        for (int i = 0; i < 3; i++) {
            System.out.print("Nome: ");
            nomes[i] = scanner.nextLine(); //armazenando em cada posição variando pelo for
            System.out.println();
        }
        for (int i = 0; i < 3; i++) System.out.println("Nome: " + nomes[i]); //acessando cada posição
    }
}

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

Browser other questions tagged

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