gpt4 book ai didi

java - 如何正确使用java中的\n

转载 作者:行者123 更新时间:2023-12-02 03:21:02 24 4
gpt4 key购买 nike

每当我编译并运行代码时,输​​出都会变得一团糟,我希望有人可以告诉我如何使我的输出看起来不错。

import java.util.*;
public class JavaApplication3 {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int NumPerHamper;
int NumHampersMade;
int NumItemsLeftOver;
int NumAvalable;
double ValuePerHamper;
double ItemCost;
double ValueAllotedHamper;
double ValueItemsLeftOver;
String name="";
Date TheDate = new Date();

System.out.println("Enter the number of avaliable mac and cheese");
NumAvalable = sc.nextInt();

System.out.println("Enter the number of items per hamper");
NumPerHamper = sc.nextInt();

System.out.println("Price Of Item");
ItemCost = sc.nextDouble();

NumHampersMade = NumAvalable / NumPerHamper;
NumItemsLeftOver = NumAvalable % NumPerHamper;
ValuePerHamper = NumPerHamper * ItemCost;
ValueAllotedHamper = ValuePerHamper * NumHampersMade;
ValueItemsLeftOver = NumItemsLeftOver * ItemCost;
System.out.printf("\n");
System.out.printf(TheDate + "\n");
System.out.printf("Amount of Hampers Made: ", NumHampersMade,"\n");
System.out.printf("The Items Left Over is: ", NumItemsLeftOver,"\n");
System.out.printf("Each Value Of the Hampers are: $%.2f.", ValuePerHamper,"\n");
System.out.printf("The Price Of All The Hampers Is: $%.2f.", ValueAllotedHamper,"\n");
System.out.printf("The Value Of Mac And Cheese Is: $%.2f.", ValueItemsLeftOver,"\n");
}
}

最佳答案

这是不对的:

System.out.printf("Each Value Of the Hampers are: $%.2f.", ValuePerHamper,"\n");

第一个参数(格式字符串)是替换“格式说明符”或占位符后实际打印的字符串。该字符串中的格式说明符(例如 %.2f)将替换为其他参数。因此,第二个参数 ValuePerHamper 用于第一个说明符 %.2f;第三个参数 \n 用于第二个说明符 ---um,但没有任何其他说明符,因此根本不会使用它。

您想要将 \n 放入格式字符串中:

System.out.printf("Each Value Of the Hampers are: $%.2f.\n", ValuePerHamper);

(printf 还允许您使用 %n 而不是 \n,这更便携,因为它也适用于 Windows 系统转到新行需要 \r\n 而不是 \n。)

关于java - 如何正确使用java中的\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39607068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com