gpt4 book ai didi

java - 不确定为什么我的代码给出 "Illegal Format Conversion Exception"错误?

转载 作者:行者123 更新时间:2023-12-01 18:18:38 32 4
gpt4 key购买 nike

我很确定错误是由最后一行引起的..据我所知,我对使用“%d”变量感到不满意。但这不是整数的有效输入吗?

import java.util.Scanner;

public class total_cost {
public static void main(String[] args) {

int TVs;
int VCRs;
int controller;
int CD;
int recorder;
double TV_price;
double VCR_price;
double controller_price;
double CD_price;
double recorder_price;
double tax;
{
TV_price = 400.00;
VCR_price = 220.00;
controller_price = 35.20;
CD_price = 300.00;
recorder_price = 150.00;
tax = .0825;

Scanner in = new Scanner(System.in);
{
System.out.printf("How many TV's were sold? ");
TVs = in.nextInt();

System.out.printf("How many VCR's were sold? ");
VCRs = in.nextInt();

System.out.printf("How many remote controller's were sold? ");
controller = in.nextInt();

System.out.printf("How many CD players were sold? ");
CD = in.nextInt();

System.out.printf("How many Tape Recorder's were sold? ");
recorder = in.nextInt();

System.out.printf("QTY\tDESCRIPTION\tUNIT PRICE\tTOTAL PRICE\n");
System.out.printf("%d", TVs + "\tTelevision\t%f", TV_price
+ "\t" + tax * TV_price + "%f", TV_price);
}
}
}
}

错误消息:

Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String
at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4011)
at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2725)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2677)
at java.util.Formatter.format(Formatter.java:2449)
at java.util.Formatter.format(Formatter.java:2383)
at java.lang.String.format(String.java:2781)
at total_cost.main(total_cost.java:37)

最佳答案

您传递的是字符串,而不是整数。应该是这样的:

System.out.printf("%d\tTelevision\t%.2f\t%.2f,%.2f", TVs, TV_price,tax * TV_price, TV_price);

PS:我可以自由地将价格格式化为小数点后两位。

关于java - 不确定为什么我的代码给出 "Illegal Format Conversion Exception"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28223514/

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