簡體   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