2012-08-01 91 views
0

我在使用我的JAVA命令行菜單時遇到了問題。這是我得到的。我想要做的是在評論中。For Each Loop to return search string

private void listStudents(){ 
    out.println("\n\tStudent Listing"); 
    //Call datastore method that returns all student names as an array of strings 
    String[] list = data.getStudents(); 
    //Display all names (use foreach statement) 
    for (String name : list) { 

    } 
} 

這裏的數據存儲方法,我也堅持了...

String[] getStudents() { 
    return (String[]) students.toArray(); 
} 

// Method to return students who match search term 
String[] findStudents(String searchTerms) { 
// Use foreach loop to visit each item in students ArrayList, 
// and if the name matches the search term, add it to a new ArraList. 
// Then return the new ArrayList as a string array (see getStudents) 
} 
+4

歡迎StackOverflow上。如果你堅持使用這種方法,你實際上嘗試過哪些方法無效?我們很樂意提供幫助,但這幾乎是一個「展示你的工作」類型的網站 - 當你說一些不起作用的東西時,應該包括什麼不起作用。 :-) – 2012-08-01 01:49:30

+0

@KenWhite謝謝。嗯,我沒有真正嘗試過任何東西,我完全不知道該怎麼做。感謝您的介紹:) – 2012-08-03 02:25:59

回答

0

你沒有定義searchterms威力的東西。這是一個正則表達式嗎?它是通配符嗎?

public String[] findStudents(String searchTerms) { 
    List<String> findList = new ArrayList<String>(25); 
    for (String student : students) { 

     // Now you'll need to define how the match works, 
     // Are you using a regexp or some kind of other matching 
     // algorithm.. 
     boolean match = ...; 
     if (match) { 

      findList.add(student); 

     } 

    } 

    return findList.toArray(new String[findList.size()]); 
} 
2

不知道如果這正是你所需要的,但根據我從您的意見了解,請嘗試使用以下:

private void listStudents() 
{ 
    System.out.println("\n\tStudent Listing"); 

    String[] list = data.getStudents(); 

    // List each student. 
    for (String name : list) 
     System.out.println(name); 
} 

private String[] findStudents(String searchTerms) 
{ 
    List<String> studentsFound = new ArrayList<String>(); 

    for (String student : students) 
    { 
     // Determine if matching student found. 
     if (student.equals(searchTerms)) 
      studentsFound.add(student); 
    } 

    return studentsFound.toArray(new String[0]); 
}