实施方法
public void search (String searchString) { }
迭代注释ArrayList直到它 找到包含searchString的注释。 然后它应该打印找到的项目或 消息“未找到字符串”。
到目前为止,我有:
import java.util.ArrayList;
import java.util.Iterator;
/**
* A class to maintain an arbitrarily long list of notes.
* Notes are numbered for external reference by a human user.
* In this version, note numbers start at 0.
*
* @author David J. Barnes and Michael Kolling.
* @version 2008.03.30
*/
public class Notebook
{
// Storage for an arbitrary number of notes.
private ArrayList<String> notes;
/**
* Perform any initialization that is required for the
* notebook.
*/
public Notebook()
{
notes = new ArrayList<String>();
}
/**
* Store a new note into the notebook.
* @param note The note to be stored.
*/
public void storeNote(String note)
{
notes.add(note);
}
/**
* @return The number of notes currently in the notebook.
*/
public int numberOfNotes()
{
return notes.size();
}
/**
* Show a note.
* @param noteNumber The number of the note to be shown.
*/
public void showNote(int noteNumber)
{
if(noteNumber < 0) {
// This is not a valid note number, so do nothing.
System.out.println("invalid index given");
}
else if(noteNumber < numberOfNotes()) {
// This is a valid note number, so we can print it.
System.out.println(notes.get(noteNumber));
}
else {
System.out.println("there are fewer items in the notebook");
// This is not a valid note number, so do nothing.
}
}
public void removeNote(int noteNumber)
{
if(noteNumber < 0) {
// This is not a valid note number, so do nothing.
System.out.println("invalid index given");
}
else if(noteNumber < numberOfNotes()) {
// This is a valid note number.
notes.remove(noteNumber);
}
else {
System.out.println("there are fewer items in the notebook");
// This is not a valid note number, so do nothing.
}
}
/* Edit note.
* I tried to improve the formatting of the code below, but I'm completely
* unable to figure out how on earth anything of that should make sense
* and therefore the indentation is completely without any meaning.
*/
public void search (String searchString)
{
for each notes in ArrayList {
if notes = searchString;
System.out.println("String found"); + searchString
return end
}
if}
System.out.println("String not found");
}
}
但它不起作用,我无法解决这个问题。
答案 0 :(得分:5)
几个问题:
search
方法实际上在课堂外。如果你依靠写莎士比亚的猴子,你会等待一段时间。
答案 1 :(得分:3)
要迭代数组列表,您可以使用'for-each' loop:
for (String note: notes) {
// Do something with note
}
这是非常基本的语法。你以前见过吗?如果没有,您应该在尝试这项功课之前先阅读一本非常基本的Java教程。
答案 2 :(得分:3)
从根本上说,您需要查看ArrayList中的每个项目并测试它是否与搜索条件匹配。在伪代码中
for each note in notes
{
if note equals searchString then
print "Found " + searchString
return
end if
}
print "not found"
鉴于基本概要,想在Java中编写它的第二次尝试?
答案 3 :(得分:2)
基本上你想循环遍历元素,并为每个元素检查它是否等于你要搜索的元素。您可以使用for循环或foreach循环来进行实际迭代。
答案 4 :(得分:2)
你应该检查整个音符是否与你的搜索字符串匹配,或者音符是否包含你的搜索字符串?
即。给出“foobar”,“baz”,“垃圾邮件”的注释,如果搜索“foo”返回“foobar”或不匹配任何内容?
所以在伪代码中:
for each note in notes
{
if searchstring in note
{
print "Found :"+note
}
}
答案 5 :(得分:1)