2015-10-12 63 views
0

我還是相當新的Java和理解一切的基礎知識,我們剛剛開始談論方法。如何添加一個額外的方法來獲得字數和字符串的第一個字

我很難實現這個新的方法..不使用數組或矢量或任何排序..
任何幫助將不勝感激!

public class ClosedLab07{ 

    public static void main(String[] args) { 

     Scanner keyboard = new Scanner (System.in); 
     String str = getInputString(keyboard); 
     int count = getWordCount(str); 
     System.out.println("Your string has " + (count+1) + " words in it."); 
     // Fill in the body with your code 
    } 

    // Given a Scanner, prompt the user for a String. If the user enters an empty 
    // String, report an error message and ask for a non-empty String. Return the 
    // String to the calling program. 
    private static String getInputString(Scanner inScanner) { 
     String str = ""; 
     while (str.equals("")){ 
      System.out.print("Enter a string: "); 
      str = inScanner.nextLine(); 
      if (str.equals("")){ 
       System.out.println("ERROR - string must not be empty."); 
       System.out.println(); 
      } 
     } 
     return str; 
     // Fill in the body 

     // NOTE: Do not declare a Scanner in the body of this method. 
    } 


    // Given a String return the number of words in the String. A word is a sequence of 
    // characters with no spaces. Write this method so that the function call: 
    //  int count = getWordCount("The quick brown fox jumped"); 
    // results in count having a value of 5. You will call this method from the main method. 
    // For this assignment you may assume that 
    // words will be separated by exactly one space. 
    private static int getWordCount(String input) { 

     int i = 0; 
     int wordCount = 0; 
     while (i < input.length()){ 
      char pos = input.charAt(i); 
      if (pos == ' '){ 
       wordCount++; 
      } 
      i++;    
     } 
     return wordCount; 
     // Fill in the body 
    } 
private static String getFirstWord(String input) 
     // THIS IS THE METHOD I'M WORKING ON 
    } 
+0

提示:字符串中有一個叫做'子()'方法。 –

+0

找到字符串中第一個空格的索引並使用上面提到的'substring()'。 – YoungHobbit

+0

private static String getFirstWord(String input){ \t \t String firstWord =「」; \t \t String str =「」; \t \t int d = str.indexOf('');如果(d> 0){ \t \t如果(d> 0){ \t \t System.out.println(「。」+ str.substring(0,d)+「。」);其他{ \t \t} else { \t \t System.out.println(「。」+ str +「。」); \t \t} \t \t return str.substring(0,d); \t}這是我的邏輯,但我不知道如何回到主體,並讓所有東西都運行。 –

回答

0

此行添加到您的新方法

return input.split("\\s")[0]; // split returns an array of all the words. you need just the first word 
相關問題