为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 270 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信