在我的程序中,我通过使用Integer.parseInt() 方法从字符串中创建了一个int,现在我已经在计算中使用它之后必须打印某些内容,但是出现错误。它直接打印直到装入特征的点。我无法格式化我从解析方法创建的int。
任何帮助表示赞赏!
这是我得到的错误,如果它是有用的。大胆的部分是程序在发生错误之前打印多远。
**您已赢得:$ **线程“main”中的异常java.util.IllegalFormatConversionException:f!= java.lang.Integer at java.util.Formatter $ FormatSpecifier.failConversion(Formatter.java:4302 ) at java.util.Formatter $ FormatSpecifier.printFloat(Formatter.java:2806) at java.util.Formatter $ FormatSpecifier.print(Formatter.java:2753) at java.util.Formatter.format(Formatter.java :2520) 在java.io.PrintStream.format(PrintStream.java:970) 在java.io.PrintStream.printf(PrintStream.java:871) 在SlotMachine.main(SlotMachine.java:50)
//variables declared
//BALANCE is declared as a constant
String userBet, dollar, coins;
int decimal, winnings, dollarToInt, coinsToInt, bet;
int slot1, slot2, slot3;
//changing users inputted string to int
do {
System.out.print("Enter your bet (or 0 to quit): $");
userBet = kbd.nextLine();
decimal = userBet.indexOf(".");
dollar = userBet.substring(0, (decimal));
coins = userBet.substring(decimal+1);
dollarToInt = Integer.parseInt(dollar);
coinsToInt = Integer.parseInt(coins);
bet = (dollarToInt*100) + (coinsToInt);
//calculating winnings and new balance
if (slot1 == slot2) {
winnings = (slot1 * bet/2);
System.out.printf("You have won: $%.2f\n", (winnings));
System.out.printf("Balance: $%.2f\n\n", (winnings - bet + BALANCE));
if (slot1 == slot3) {
winnings = (slot1 * bet/2);
System.out.printf("You have won: $%.2f\n", (winnings));
System.out.printf("Balance: $%.2f\n\n", (winnings - bet + BALANCE));
}
if (slot2 == slot3) {
winnings = (slot2 * bet/2);
System.out.printf("You have won: $%.2f\n", (winnings));
System.out.printf("Balance: $%.2f\n\n", (winnings - bet + BALANCE));
}
因此,要将其格式化为int,我会使用(%.2d)吗? – T3rm3nator
因为这样做,它甚至提前发生错误,甚至不打印“你赢了:$” – T3rm3nator
尝试更改'System.out.printf(“你赢了:$%。2f \ n”,(赢钱)) ;'to'System.out.printf(“你赢了:$%。2f \ n”,(float)(winnings/100));' – user5151179