猿问

BASIC,在调用 %d%n 后不能输出任何其他字符串吗?

import java.util.*; //for %d%n

import java.text.*; //for DecimalFormat



public 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"


    }

    }


慕的地8271018
浏览 271回答 3
3回答

UYOU

您的代码的替代解决方案;System.out.printf("With a cash stack of "             + cashStack             + " we can buy "             + "%.0f ", maxAmount).println(itemName);所以你不能混淆 printf 和 println 的用法。

MM们

要在此处完成其他答案,在使用 printf 时,我会避免在格式字符串中连接变量并执行以下操作:System.out.printf("With a cash stack of %.0f we can buy %.0f %s%n", cashStack, maxAmount, itemName);的语法printf是public 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);

慕森王

将您的打印语句更改为%s(对于 a String)而不是%n(这是一个换行符)System.out.printf("With a cash stack of "                 + cashStack                 + " we can buy "                 + "%.0f %s", maxAmount, itemName);
随时随地看视频慕课网APP

相关分类

Java
我要回答