简体   繁体   中英

Java ArrayList, how to list one at a time?

So I am just doing a quick exception program where I just ask the user to input 10 names and the names will be transferred to a .txt file. I have to us an arrayList, so the problem I have now is, every time the user inputs a name, the counsel will output all the previous names before it as well. Can someone please show me how to print the ArrayList one at a time?

Ex. Please enter name 1: Wei
Please enter name 2: ming
Please enter name 3: guo

At the moment, this is how my output looks like:

    /*      
* Please enter name 1:[wei]
Please enter name 2:[wei, ming]
Please enter name 3:[wei, ming, guo]
Please enter name 4:[wei, ming, guo, wei]
Please enter name 5:[wei, ming, guo, wei, ming]
Please enter name 6:[wei, ming, guo, wei, ming, dfuo]
Please enter name 7:[wei, ming, guo, wei, ming, dfuo, wer]
Please enter name 8:[wei, ming, guo, wei, ming, dfuo, wer, sdf]
Please enter name 9:[wei, ming, guo, wei, ming, dfuo, wer, sdf, sdf]
Please enter name 10:[wei, ming, guo, wei, ming, dfuo, wer, sdf, sdf, sdf]
*/

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class NamesDemo {

    public static void main(String[] args) {
        String NamesDemo = "names.txt";
        PrintWriter outputStream = null;
        try {
            outputStream = new PrintWriter(NamesDemo);
        } catch (FileNotFoundException e) {
            System.out.println("Error opening the file " + NamesDemo);
            System.exit(0);
        }

        System.out.println("Enter 10 names: ");
        Scanner kb = new Scanner(System.in);
        ArrayList<String> name = new ArrayList<String>();

        for (int i = 0; i < 10; i++) {
            name.add(kb.next());
            outputStream.println("Please enter name " + (i + 1) + ":" + name);

        }
        outputStream.close();
        System.out.println("Thse names were sent to file: " + NamesDemo);
    }

}

Simply print the last entered value instead of the whole list :

for (int i =0; i<10; i++){
    String newValue = kb.next();
    name.add(newValue);
    outputStream.println("Please enter name " + (i+1) + ":" + newValue);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM