在我的程序中,我通過使用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