类型不匹配无法从元素类型对象转换为字符串 [英] type mismatch cannot convert from element type object to string

查看:869
本文介绍了类型不匹配无法从元素类型对象转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中使用搜索方法搜索字符串时,我一直收到此错误。我已经经历了很多试图解决这个问题的例子,但是我找不到。感谢您的帮助和建议,您可以给予。

I keep getting this error when making a search method in my code to search through string. I have gone through alot of examples trying to fix this but I cant find any. Thank you for any help and advise you can give.

public class runNote {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Notebook note = new Notebook();
    note.storeNote("happy");
    note.storeNote("hello there");
    note.storeNote("work at 5");
    note.storeNote("BBQ Time");
    note.storeNote("UNI!!!!");
    note.storeNote("Dont miss lecture at 9:15");
    System.out.println(note.numberOfNotes());
    note.showNote(1);
    note.searchNotes("hap");

}}




public class Notebook{


/**
 * Perform any initialization that is required for the
 * notebook.
 */
public Notebook()
{
    notes = new ArrayList();
}

/**
 * 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();
}

/**
 * A simple search engine to find the correct notes.
 */
public void searchNotes(String search){ 
    for (String item : notes){
        if (item.contains(search)){
        System.out.println(item);
        }
    }
}

/**
 * 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.
    }
}
}


推荐答案

将笔记作为全局变量添加到您的班级

Add notes as a global variable to your class

public class Notebook{
ArrayList<String> notes = null;

....
}

在构造函数中,执行:

public Notebook()
{
    notes = new ArrayList<String>();
}

这篇关于类型不匹配无法从元素类型对象转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆