gpt4 book ai didi

java - 找不到符号 - 类迭代器 [Java]

转载 作者:行者123 更新时间:2023-12-01 07:05:18 24 4
gpt4 key购买 nike

我刚刚开始使用 Java 并收到错误:“找不到符号 - 类迭代器”

我的代码有什么问题吗?

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.
}
else if(noteNumber < numberOfNotes()) {
// This is a valid note number, so we can print it.
System.out.println(notes.get(noteNumber));
}
else {
// This is not a valid note number, so do nothing.
}
}

public void removeNote(int noteNumber)
{
if(noteNumber < 0){
System.out.println("The index cannot be less than 0");
}
else if(noteNumber < numberOfNotes()){
System.out.println("This is a valid note number so remove");
notes.remove(noteNumber);
}
else {
System.out.println("The index cannot be greater than the number of notes");
}
}

public void listNotesForEach()
{
for(String note : notes){
System.out.println(note);
}
}

public void listNotesWhile()
{
int index = 0;
while(index < notes.size()) {
System.out.println(notes.get(index));
index++;
}
}

public boolean hasNote(String searchString)
{
int index = 0;
boolean found = false;
while(index < notes.size() && !found) {
String note = notes.get(index);
if(note.contains(searchString)) {
//we don't need to keep looking
found = true;
}
else {
index++;
}
}
//Either we found it, or we searched the whole collection return found;
return found;
}
public void showNotes(String searchString)
{
int index = 0;
boolean found = false;
while(index < notes.size() && !found) {
String note = notes.get(index);
if(note.contains(searchString)) {
System.out.println(index + " : " + note);
}
index++;
}
}
public void listNotesIterator()
{
Iterator<String> it = notes.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}

}

最佳答案

您的错误消息告诉您它不知道类Iterator

使用 import 语句可以解决这个问题。

在代码上方添加import java.util.Iterator;

一般来说,只要您使用的类不在内置 java.lang 包中,您就需要导入该类。常见的例子来自java.util.ClassHere,比如

import java.util.List; // Class to hold a list of objects
import java.util.Scanner; // Class to read in keyboard etc entry
// my code here

关于java - 找不到符号 - 类迭代器 [Java],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26732819/

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