Java程序将字符串作为用户输入并将其存储在数组中,然后将其打印

问题描述

如果我无法解释这个问题,我很抱歉。当我接受用户输入时,它只打印字符串的第一个单词。 帮助我了解我缺少什么,或者当我接受用户输入时为什么它不起作用。

当我传递输入“This is Mango”时,它只打印 This

相反,我想将其打印为 This is Mango

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter the String: ");
    String str= in.next();

    String[] words = str.split("[[ ]*|[//.]]");
    for(int i=0;i<words.length;i++)
        System.out.println(words[i]+" ");

如果我给出一个硬编码的字符串,它可以将它保存在数组中。

String str = "This is a sample sentence.";
String[] words = str.split("[[ ]*|[//.]]");
for(int i=0;i<words.length;i++)
    System.out.println(words[i]+" ");

当我运行上面的代码时,它打印为

This is a sample sentence

解决方法

更改这一行:

String str = in.next();

为此:

String str = in.nextLine();

这样,您的 Scanner 对象将读取整行输入。

如果您只使用 next(),它只会读取输入,直到遇到空格。同时, nextLine() 读取整行(直到您在提供输入时转义到下一行)。另请注意,如果您想读取其他数据类型,则需要使用相应的函数。例如,要读取一个整数,您应该使用 nextInt()

希望这会有所帮助!

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...