这是我到目前为止所做的,但我现在不知道接下来要做什么。问题如下(抱歉,编码并非全部出现在一个方框中): 实现方法
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 than that");
// 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 than that");
// This is not a valid note number, so do nothing.
}
}
public void multiplesOfFive()
{
int i = 10;
while(i < 100)
{
System.out.println(i);
i = i + 5;
}
}
public int sum(int a, int b)
{
int index = a;
int result = 0;
while(index <= b)
{
result = result + index;
index = index + 1;
}
return result;
}
public int product(int a, int b)
{
int index = a;
int result = 1;
while(index <= b)
{
result = result * index;
index = index + 1;
}
return result;
}
public boolean
isPrime (int n)
{
if (n<=1)return false;
if (n==2) return true;
for (int i = 2;i<=n-1;i++)
{
if (n%i==0)return false;
}
return true;
}
}
答案 0 :(得分:1)
要考虑两个想法:
contains
方法(请参阅Kaleb Brasee的帖子)。null
作为搜索参数传入时处理该案例。 答案 1 :(得分:0)
使用新的for-each style loops之一迭代笔记列表:
for (String string : notes) {
// This will loop over all the Strings in the notes List.
// Perform your logic here.
}
答案 2 :(得分:0)
如果列表不是按字母顺序排列,则需要遍历列表,将每个字符串与搜索字符串进行比较。一旦找到匹配就可以打破循环(使用return true(或字符串)将是最简单的方法)然后在循环外你可以返回false表示没有找到匹配。
您需要使用的一些方法:
的 的ArrayList 强>:
字符串:
最好熟悉Java API,以便找到方法及其返回值。
如果列表按字母顺序排列,则可以采用更有效的方式进行搜索。