Java 编译错误 - 类型不匹配 : cannot convert from String to int

标签 java compiler-errors

问题是 Meadowdale Dairy Farm 向本地客户出售有机棕色鸡蛋。一打鸡蛋收费 3.25 美元,不属于一打的单个鸡蛋收费 45 美分。编写一个程序,提示用户输入订单中的鸡蛋数量,然后显示欠款金额并给出完整说明。例如,典型输出可能是,您订购了 27 个鸡蛋。那是 2 打,每打 3.25 美元,3 个散装鸡蛋,每个 45 美分,总共 7.85 美元。将程序另存为 EggsTwo.java。

这就是我所拥有的:

import javax.swing.JOptionPane;
public class EggsTwo
{
    public static void main(String[] args)
    {
        int eggs, dozen, individual;
        double price;
        final double priceOfDozen = 3.25;
        final double priceOfIndividual = 0.45;

        eggs = JOptionPane.showInputDialog(null, "Enter the number of eggs in the order.", "Eggs 
        Dialog 1", JOptionPane.INFORMATION_MESSAGE);
        dozen = eggs / 12; 
        individual = eggs % 12;
        price = (dozen * priceOfDozen) + (individual * priceOfIndividual);
        JOptionPane.showMessageDialog(null, "You ordered " + eggs + " eggs. That's " + dozen + " 
        dozen and " + individual + " loose eggs at 45 cents each for a total of $" + price + ".");
    }
}

最佳答案

方法showInputDialog实际上返回一个 String ,这就是您收到错误的原因,这很清楚。

eggs = Integer.valueOf(JOptionPane.showInputDialog(null, "Enter the number of eggs in the order.", "Eggs 
        Dialog 1", JOptionPane.INFORMATION_MESSAGE));

您必须先将其转换为整数。

关于Java 编译错误 - 类型不匹配 : cannot convert from String to int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59709478/

相关文章:

java - 如何配置邮件服务器以与 JavaMail 一起使用?

c++ - 创建全局变量导致链接器错误

c++ - C 与 C++ : How to fix? Typedef 枚举

C语言编程错误: expected specifier-qualifier-list before '{ '

python - Python不断显示 'object has no such attribute'

c++ - 使用已在另一个已用库中定义的函数名称的库

java - 为什么我的函数给出无限输出?

java - 我可以在 Firebase 数据库中存储 Int 值吗

java - 在java中比较两个字符串与Date

java - 如何使用 MyBatis 获取 Oracle 中的最后插入 ID?