gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:13:57 25 4
gpt4 key购买 nike

问题是 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/

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