我刚刚开始使用Java并收到错误:"找不到符号 - 类Iterator"
我的代码出了什么问题?
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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
您的错误消息告诉您它不知道该类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
Run Code Online (Sandbox Code Playgroud)