2016-03-18 31 views
-1

我將如何讓一個while循環遍歷字符串的字符來找到第一個空格並返回該位置的值。我是否需要在while循環中使用雙重條件?如何使此測試通過?

public class TestSentenceCounter 
{ 
private static final String SENTENCE1 = "This is my sentence."; 
private static final String SENTENCE2 = "These words make another sentence that is longer"; 
private SentenceCounter sc1; 
private SentenceCounter sc2; 

/** 
* Create two instances we can play with 
*/ 
@Before 
public void setup() 
{ 
    sc1 = new SentenceCounter(SENTENCE1); 
    sc2 = new SentenceCounter(SENTENCE2); 
} 
/** 
* Make sure the instance variable is correct 
*/ 
@Test 
public void testConstructor() 
{ 
    assertEquals(SENTENCE1, sc1.getSentence()); 
    assertEquals(SENTENCE2, sc2.getSentence()); 
} 
@Test 
public void testFirstBlankPosition() 
{ 
    assertEquals(4, sc1.firstBlankPosition()); 
    assertEquals(5, sc2.firstBlankPosition()); 
} 
} 
---------------------------------------------------- 
public class SentenceCounter 
{ 
public String sentence; 

public SentenceCounter(String sentence) 
{ 
    this.sentence = sentence; 
} 

public Object getSentence() 
{ 

    return sentence; 
} 
public Object firstBlankPosition() 
{ 


    return null; 
} 
} 
+0

它爲我的實驗班,我的報告廳老師是國外的,所以要真正瞭解編碼的唯一途徑是從Reddit和在這裏,我們應該使用一個while循環來找到它,這只是非常基本的Java教學 – Wert2

回答

0

更新代碼,因此,

public int firstBlankPosition() 
{ 

     int returnVal = 0; 
     char ch ; 
      for(int i = 0 ; i < sentence.length() ; i++){ 
       ch = sentence.charAt(i); 

       if(ch == ' '){ 
        returnVal = i; 
        break; 
       } 
      } 

    return returnVal; 
}