Show string string typed

1

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

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

?? < - Make read names appear here

    
asked by anonymous 15.02.2017 / 20:16

1 answer

1

You will have to use an array ( vector ) so that a variable has multiple indexed memory locations. Already seized womb at school? It's basically an array with a single dimension.

Sointhisexampleweactuallyhave10variablesinmemorythatareaccessedbyanameandanindexandavariablethatencompassesthosevariablesthatcanbeaccessedbyname,butwithoutindexcannotaccesswhatisinsideit.>

Bracketsareusedtoindicatetheindexthatwillbeaccessedinthisvariable.

The array always starts at 0 , so I changed its for .

Without the vector each repeat cycle of for will erase the value previously stored in the variable, then you have to reserve positions for all the entries you want to enter, the array is the solution. p>

Of course in a simple example like this could have created 3 variables and not have a loop, but I imagine you are wanting to do the way you do in real applications. If it was 100, I'd just change the number there. This 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 will have and allocate dynamically, or you will use a list in place of the array and add as long as the person is entering new entries. But that leaves the next.

You can improve this code, but we will not do it all 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
        }
    }
}

See working at ideone . And on the Coding Ground . I also put it in the GitHub for future reference.

    
15.02.2017 / 20:38