gpt4 book ai didi

java - 搜索字符串的 ArrayList 以查找文本

转载 作者:行者123 更新时间:2023-12-01 16:09:07 26 4
gpt4 key购买 nike

这是我到目前为止所拥有的,但我现在不知道下一步该做什么。问题如下(抱歉,编码没有全部出现在一个框中):实现一个方法

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;
}
}

最佳答案

需要考虑的两个想法:

  1. 在制定搜索方法时,请考虑使用 contains迭代时 String 类中的方法(请参阅 Kaleb Brasee 的帖子)。
  2. 确保在将 null 作为搜索参数传入时处理这种情况。

关于java - 搜索字符串的 ArrayList 以查找文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1877640/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com