gpt4 book ai didi

java - 分割用户输入的字符串,然后打印该字符串

转载 作者:行者123 更新时间:2023-12-02 09:13:37 25 4
gpt4 key购买 nike

我正在进行一项自学,本质上我是要求用户输入字符串,例如“John,Doe”如果该字符串没有逗号,我将显示错误,并提示用户直到字符串确实有逗号(已修复。)。实现此目的后,我需要从逗号以及可能出现的任何逗号组合解析字符串(即 John, doeJohn , doeJohn ,doe),然后使用 Scanner 类,我需要抓取 John doe,并将它们分开以便稍后单独打印。

到目前为止,我知道如何使用扫描器类来抓取一定数量的字符串直到空格,但是我想要的是抓取“,”,但我想我还没有找到一种方法来做到这一点我需要使用扫描仪类的 .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]

编辑

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

关于java - 分割用户输入的字符串,然后打印该字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59186187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com