Java错误,不兼容的类型:对象无法转换为字符串

时间:2016-08-27 19:10:36

标签: java incompatibletypeerror

我差不多完成了创建这个简单的代码,但是在从JOptionPane创建输入对话框并给它一个变量时,我一直收到错误。

例如:

name = JOptionPane.showInputDialog(null, "What is your name?",
                    "Question",
                    JOptionPane.QUESTION_MESSAGE,
                    iconhello,
                    null,
                    "");

当名称在前面时,我得到错误,当它没有错误并且我的代码运行顺利时,但是我需要将输入返回到我稍后在代码中创建的消息对话框。

这是完整的代码:

public static void main(String[] args) {
    String name, choice, choice2, choice3, order;
    ImageIcon iconhello;//identifying the new icon created
    iconhello = new ImageIcon("hello.gif");

    ImageIcon iconcat1;
    iconcat1 = new ImageIcon("cat1.gif");

    ImageIcon iconcat7;
    iconcat7 = new ImageIcon("cat7.gif");

    ImageIcon icondrink;
    icondrink = new ImageIcon("drink.gif");

    ImageIcon iconpizza;
    iconpizza = new ImageIcon("pizza.gif");

          name = JOptionPane.showInputDialog(null, "What is your name?",
                    "Question",
                    JOptionPane.QUESTION_MESSAGE,
                    iconhello,
                    null,
                    "");

    Object[] possibilities= {"Chicken Sub", "Chicken Teriyaki Sub", "Tuna "
            + "Sub", "Vegetable Sub"};//creating options for user to choose from

    choice= (String)JOptionPane.showInputDialog(null, "What type of"
            + " subsandwich do you like? \n \"I like...\"",
    "Subsandwich",
    JOptionPane.QUESTION_MESSAGE,
    iconpizza,
    possibilities,
    "Chicken Sub");

    Object[] possibilities1= {"Sprite", "Coke", "7Up", "Pepsi"};

    choice2= (String)JOptionPane.showInputDialog(null, "What type of"
    + " drink do you prefer to have? \n \"I prefer..\"",
    "Drink",
    JOptionPane.QUESTION_MESSAGE,
    icondrink,
    possibilities1,
    "Sprite");

    JOptionPane.showInputDialog(null, "Please state what you would like"
            + " to have additionally",
            "Additional Request",
            JOptionPane.INFORMATION_MESSAGE,
            iconcat1,
            null,
            "");

    order= String.format("Your order: \n " + choice + " \n" + choice2 + 
            " \n Please enjoy!",
            "Order for: " + name + " " ,
            JOptionPane.PLAIN_MESSAGE,
            iconcat7,
            null);
    JOptionPane.showMessageDialog(null, order);


}

如果可以,请帮助我。

1 个答案:

答案 0 :(得分:3)

您正在调用的showInputDialog方法返回Object,但您将返回的值分配给String变量。错误消息告诉您Java不会隐式为您进行此转换,您必须明确地执行此操作。你已经在代码的后面几行了。

choice = (String)JOptionPane.showInputDialog(null, "What type of"
            + " subsandwich do you like? \n \"I like...\"",
    "Subsandwich",
    JOptionPane.QUESTION_MESSAGE,
    iconpizza,
    possibilities,
    "Chicken Sub");
相关问题