如何使用Java在Array中接受用户输入? [英] how to take user input in Array using java?

查看:94
本文介绍了如何使用Java在Array中接受用户输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Java在Array中接受用户输入? 即我们不是在程序中自行初始化它,而是用户要赋予它的价值. 请指导!

how to take user input in Array using Java? i.e we are not initializing it by ourself in our program but the user is going to give its value.. please guide!!

推荐答案

下面是一个简单的代码,它从stdin中读取字符串,将它们添加到List<String>中,然后使用toArray将其转换为String[](如果您真的需要使用数组).

Here's a simple code that reads strings from stdin, adds them into List<String>, and then uses toArray to convert it to String[] (if you really need to work with arrays).

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));
    }
}


另请参见:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆