【问题标题】:How to store user input if it was something like a sentence? Or if it was someones name? [duplicate]如果它是一个句子,如何存储用户输入?或者如果它是某人的名字? [复制]
【发布时间】:2020-02-19 01:35:46
【问题描述】:

类似于我的旧问题。有没有办法可以将用户输入的内容存储到数组中,以便我可以通过 stringName[1] 或 stringName[2] 调用它? 我不精通java拆分。 例如,如果我有

System.out.println ("A sentence or your full name please" );
for (int j = 0; j < arrayTwo.length; j++){
array[j]= sc.nextLine();
System.out.println(array[0]);

这只会打印出名字

如果用户输入“John Will Smith”然后我想打印出来

System.out.println (+firstName);
System.out.println (+middleName);
System.out.println (+lastName);

如何单独更新数组或拆分数组以获取用户输入的内容?

【问题讨论】:

    标签: java arrays string split


    【解决方案1】:

    在这里使用for 循环似乎没用。将字符串读取为一行,然后用空格将其拆分。检查以下代码:

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("A sentence or your full name please");
        String fullName = scanner.nextLine(); //Read the full name
        String[] nameArray = fullName.split("\\s+"); //Split the full name by white spaces and insert it to array
        for (String name : nameArray) { //Print names in array
            System.out.println(name);
        }
    }
    

    【讨论】:

    • 这给了我一个错误
    • @River 你能告诉我错误吗?
    猜你喜欢
    • 2021-08-16
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 2021-08-16
    相关资源
    最近更新 更多