How to use java to get user input in array?

How to get user input in array using Java?

Solution

This is a simple code to read strings from stdin, add them to list < string >, and then use toArray to convert them to string [] (if you really need to use array)

import java.util.*;

public class UserInput {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        Scanner stdin = new Scanner(system.in);

        do {
            System.out.println("Current list is " + list);
            System.out.println("Add more? (y/n)");
            if (stdin.next().startsWith("y")) {
                System.out.println("Enter : ");
                list.add(stdin.next());
            } else {
                break;
            }
        } while (true);
        stdin.close();
        System.out.println("List is " + list);
        String[] arr = list.toArray(new String[0]);
        System.out.println("Array is " + Arrays.toString(arr));
    }
}

You can also see:

> Why is it preferred to use Lists instead of Arrays in Java? > Fill a array with List data

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>