![](/img/trans.png)
[英]Type mismatch: cannot convert from int to int[] error in Java code
[英]Java Compilation Error- Type mismatch: cannot convert from String to int
問題是 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));
您必須先將其轉換為整數。
JOptionPane.showInputDialog 方法返回一個字符串。 您需要像這樣解析 Integer 的返回值:
String EggValueString = JOption... Eggs = Integer.parseInt(eggsValeuString);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.