如何正确使用java中的\ n

时间:2016-09-21 03:31:05

标签: java

每当我编译并运行我的代码时,输​​出变得很乱,我想如果有人能告诉我如何使我的输出看起来很好。

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");
    }
}

2 个答案:

答案 0 :(得分:1)

这是不对的:

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

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

您希望将\n放在格式字符串中:

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

printf还允许您使用%n而不是\n,这更便于携带,因为它也适用于需要{{1}新线路的Windows系统而不是\r\n。)

答案 1 :(得分:1)

您可以使用<!DOCTYPE html> <html> <head> <style> div { width: 90px; height: 20px; background-color: yellow; /* Rotate div */ transform: rotate(270deg); } </style> </head> <body> <div><font color="red"><b>ACTIVE</b></font></div> </body> </html> %n。这些中的任何一个都应该放在\n方法的第一个参数中。

printf()

您缺少System.out.printf("Each Value Of the Hampers are: $%.2f. %n", ValuePerHamper); System.out.printf("The Price Of All The Hampers Is: $%.2f.%n", ValueAllotedHamper); System.out.printf("The Value Of Mac And Cheese Is: $%.2f.%n", ValueItemsLeftOver); ,前两行显示值。

%d