繁体   English   中英

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

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

我正在完成一项自学,本质上我是要求用户输入一个字符串,例如“John, Doe”如果字符串没有逗号,我要显示错误,并提示用户直到字符串确实有一个逗号(固定。)。 一旦实现这一点,我需要解析逗号中的字符串,以及可能出现的任何逗号组合(即John, doeJohn , doeJohn ,doe )然后使用 Scanner 类我需要抓取 John doe,然后拆分它们稍后单独打印。

到目前为止,我知道如何使用扫描仪类将一定数量的字符串抓取到空白处,但是我想要的是抓取“,”但我还没有找到一种方法来做到这一点,我想使用.next(pattern)扫描仪类的.next(pattern)将是我需要的,因为它的编写方式应该做到这一点。 但是我这样做时遇到异常 InputMismatchException 。

这是我正在使用的代码:

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

       }

这可以通过拆分并检查结果是否是两个字符串的数组来实现

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]

编辑

如您所见,输入数据的代码是重复的,因此可以重构

暂无
暂无

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

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