繁体   English   中英

将逗号和空格分隔的输入分成两个词

[英]Splitting a comma and space separated input into two words

我很难将用户输入字符串分成两个词。 该字符串的格式为“ word1,word2”,我正在尝试创建两个单独的字符串,分别为word1和word2。 这是我的尝试:

System.out.println("Enter the two words separated by a comma, or 'quit':");

Scanner sc = new Scanner(System.in);

String input = sc.next();

while(!input.equals("quit")){
    input.replaceAll("\\s+","");

    System.out.println(input);  //testing

    int index1 = input.indexOf(",");

    String wordOne = input.substring(0, index1);

    String wordTwo = input.substring(index1+1, input.length() );

    if(wordOne.length()!=wordTwo.length()){
           System.out.println("Sorry, word lengths must match.");
       }

    System.out.println("Enter the two words separated by a comma, or 'quit':"); 

    input = sc.next();
}

这是输出:

Enter the two words separated by a comma, or 'quit':  
leads, golds  
leads,  
Sorry, word lengths must match.  
Enter the two words separated by a comma, or 'quit':  
golds  
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1  
    at java.lang.String.substring(String.java:1911)  
    at Solver.main(Solver.java:22) //this points to the line "String wordOne = input.substring(0, index1);"  

有人可以告诉我我要去哪里错吗?

您为什么不尝试:

input.split(",");

这将为您提供一个String数组。 从JavaDocs。

public String[] split(String regex)

围绕给定正则表达式的匹配项拆分此字符串。 该方法的工作方式就像通过调用具有给定表达式且限制参数为零的二参数拆分方法。 因此,结尾的空字符串不包括在结果数组中。

更新:因为,您正在使用sc.next() ,它将使用一个单词,除非它看到一个空格来终止输入。 您应该改用sc.nextLine()将完整的输入保留为用户输入。

next()

public java.lang.String next()查找并返回此扫描器的下一个完整令牌。 完整的标记在其前面,然后是与定界符模式匹配的输入。 即使先前调用hasNext返回true,此方法也可能在等待输入扫描时阻塞。

nextLine()

public java.lang.String nextLine()

使该扫描仪前进到当前行之外,并返回被跳过的输入。 此方法返回当前行的其余部分,但不包括最后的任何行分隔符。 该位置设置为下一行的开始。 由于此方法继续在输入中搜索以寻找行分隔符,因此,如果不存在行分隔符,它可以缓冲所有要搜索的输入以跳过该行。

问题是,你正在使用sc.next()代替sc.nextLine() 我可以看到,在您输入的内容中,您输入的是“线索,黄金”,线索后面是一个空格。 在这种情况下, sc.next()将仅返回“ leads”,而不返回“ leads,gold”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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