2013-12-13 50 views
0

我有返回基於用戶的輸入字符串中的基本方法:突破它後重新點燃條件語句?

public String getString() { 

    String message = inputGenerator.getMessage(); // Returns user inputted string 
    String messageStart = message.substring(0, 3); // Get start of message 
    String concat = ""; // Variable to concatenate messages 

    if(messageStart.equals("Hi")) { 
     concat += message; // Append input to concat string. 
     inputGenerator.getMessage(); // Call for another user prompt 
    } else { 
     concat += message; // Append input to concat string. 
    } 

    return concat; // Return concatenated string. 

} 

我想要做什麼:

正如你所希望的工作了,我想要做的如果消息的開頭包含單詞hi,直到它沒有,並且返回該連接的字符串,例如提示用戶輸入更多消息

>> Enter a string ("hiexample") 
>> Enter a string ("hianotherexample") 
>> Enter a string ("nothi") 
>> returns "hiexamplehianotherexamplenothi" 

問題

的問題是,由於inputGenerator.getMessage();被稱爲後明顯跳出條件的if語句只能使用一次。

如果我嘗試使用while()語句,它會永遠運行並最終導致程序崩潰。

+0

顯示'while'循環你正在嘗試使用。 –

+0

你可以在使用while循環時顯示你嘗試的邏輯,只是一個fyi:'「hi」.equals(「Hi」)== false' – clcto

+0

@ PM77-1 while while(messageStart.equals(「Hi 「)) – user2381114

回答

3

這似乎更短,更優雅:

public String getString() { 
    StringBuilder msg = new StringBuilder(); 
    String read; 

    do { 
     read = inputGenerator.getMessage(); 
     msg.append(read); 
    } while (read.toLowerCase().startsWith("hi")); 

    return msg.toString(); 
} 

我使用StringBuilder,因爲你喜歡做的比字符串連接更有效。 讓我解釋一下:

concat += message; 

被編譯器充氣至

concat = new StringBuilder(concat).append(message).toString(); 

現在猜測這是更有效的。 :)

+0

這是一個很好的幫助。謝謝! – user2381114

1

這是你在想什麼?

public String getString() 
{ 
    String result = ""; 

    while (true) 
    { 
     String message = inputGenerator.getMessage(); 
     result += message; 

     if (!message.startsWith("hi")) 
     { 
      break; 
     } 
    } 

    return result; 
} 

我想你想2作爲第二個參數substring因爲你的延續串"hi",對不對?編輯:感謝Floegipoky,clcto和StackOverflowException的幾個調整(見下面的評論/其他答案)。

+0

你的意思是'if(!message.substring(0,2).equals(」hi「))''而不是'if(message.substring(0,2)==」hi「)''? – tilpner

+0

據此編輯,謝謝。 – TypeIA

+0

很確定OP能弄清楚這些細節......至少我希望如此;-)這是他試圖找出的控制流。 – TypeIA