亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

BASIC,在調用 %d%n 后不能輸出任何其他字符串嗎?

BASIC,在調用 %d%n 后不能輸出任何其他字符串嗎?

慕的地8271018 2021-08-19 18:32:51
import java.util.*; //for %d%nimport java.text.*; //for DecimalFormatpublic class Favorite {public static void main(String[] arguments) {String itemName = "Golden Beans";float offerPrice = 314;float sellPrice = 321;float value = (sellPrice - offerPrice);float cashStack = 500_000;float maxAmount = (cashStack / offerPrice);float percentageProfit = ((value / offerPrice) * 100);System.out.println("Approx. Offer Price is " + "\t" + offerPrice);System.out.println("Approx. Sell Price is " + "\t" + sellPrice);System.out.println("The potential profit margin is " + value);System.out.printf("With a cash stack of " + cashStack + " we can buy " + "%.0f%n", maxAmount);//why can't I add + itemName; it gives me a compile error when using printf. I can add as much text etc before but not after using + "%.0f%n"System.out.printf("The profit margin of " + itemName + " as a percentage is "+ "%.3f%n", percentageProfit);//why can't I add text here; it gives me a compile error when using printf. I can add as much text etc before but not after using + "%.0f%n"    }    }
查看完整描述

3 回答

?
UYOU

TA貢獻1878條經驗 獲得超4個贊

您的代碼的替代解決方案;

System.out.printf("With a cash stack of "
            + cashStack
            + " we can buy "
            + "%.0f ", maxAmount).println(itemName);

所以你不能混淆 printf 和 println 的用法。


查看完整回答
反對 回復 2021-08-19
?
MM們

TA貢獻1886條經驗 獲得超2個贊

要在此處完成其他答案,在使用 printf 時,我會避免在格式字符串中連接變量并執行以下操作:

System.out.printf("With a cash stack of %.0f we can buy %.0f %s%n", cashStack, maxAmount, itemName);

語法printfpublic PrintStream format(String format, Object... args)。

當您嘗試在第二個參數后添加更多文本時,您正在嘗試將字符串添加到無法在任何類型轉換中工作的 PrintStream。

要通過一次調用打印兩行,您可以執行以下操作:

System.out.printf("With a cash stack of %.0f we can buy %.0f %s%n"
                + "The profit margin of %s as a percentage is %.3f%n", 
                cashStack, maxAmount, itemName,
                itemName, percentageProfit);


查看完整回答
反對 回復 2021-08-19
?
慕森王

TA貢獻1777條經驗 獲得超3個贊

將您的打印語句更改為%s(對于 a String)而不是%n(這是一個換行符)

System.out.printf("With a cash stack of "
                + cashStack
                + " we can buy "
                + "%.0f %s", maxAmount, itemName);


查看完整回答
反對 回復 2021-08-19
  • 3 回答
  • 0 關注
  • 297 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號