简体   繁体   English

拆分用户输入的字符串,然后打印该字符串

[英]Splitting a user inputted string and then printing the string

I am working through a piece of self study, Essentially I am to ask the User for a string input such as "John, Doe" IF the string doesnt have a comma, I am to display an error, and prompt the user until the string does indeed have a comma (Fixed.).我正在完成一项自学,本质上我是要求用户输入一个字符串,例如“John, Doe”如果字符串没有逗号,我要显示错误,并提示用户直到字符串确实有一个逗号(固定。)。 Once this is achieved I need to parse the string from the comma, and any combination of comma that can occur (ie John, doe or John , doe or John ,doe ) then using the Scanner class I need to grab John doe, and split them up to be separately printed later.一旦实现这一点,我需要解析逗号中的字符串,以及可能出现的任何逗号组合(即John, doeJohn , doeJohn ,doe )然后使用 Scanner 类我需要抓取 John doe,然后拆分它们稍后单独打印。

So far I know how to use the scanner class to grab certain amounts of string up to a whitespace, however what I want is to grab the "," but I haven't found a way to do this yet, I figured using the .next(pattern) of the scanner class would be what I need, as the way it was written should do exactly that.到目前为止,我知道如何使用扫描仪类将一定数量的字符串抓取到空白处,但是我想要的是抓取“,”但我还没有找到一种方法来做到这一点,我想使用.next(pattern)扫描仪类的.next(pattern)将是我需要的,因为它的编写方式应该做到这一点。 however im getting an exception InputMismatchException doing so.但是我这样做时遇到异常 InputMismatchException 。

Here is the code im working with:这是我正在使用的代码:

while (!userInput.contains(",")) {
           System.out.print("Enter a string seperated by a comma: ");
           userInput = scnr.nextLine();
           if (!userInput.contains(",")) {
               System.out.println("Error, no comma present");
           }
           else {
               String string1;
               String string2;
               Scanner inSS = new Scanner(userInput);

               String commaHold;
               commaHold = inSS. //FIXME this is where the problem is
               string1 = inSS.next();
               string2 = inSS.next();
               System.out.println(string1 + " " + string2);
           }

       }

This can be achieved simply by splitting and checking that the result is an array of two Strings这可以通过拆分并检查结果是否是两个字符串的数组来实现

String input = scnr.nextLine();
String [] names = input.split (",");
while (names.length != 2) {
    System.out.println ("Enter with one comma");
    input = scnr.nextLine();
    names = input.split (",");
}

// now you can use names[0] and names[1]

edit编辑

As you can see the code for inputting the data is duplicated and so could be refactored如您所见,输入数据的代码是重复的,因此可以重构

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

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