2016-09-21 127 views
0

当我编译并运行我的代码时,输​​出变得非常混乱,我想如果有人能告诉我如何让我的输出看起来不错。如何在java中正确使用 n

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

尝试使用'System.out.println'而不是'System.out.printf' – AndreFeijo

+0

为什么我复制/ PASE我的细节是,因为这个网站说,我刚刚代码,并没有任何细节的唯一原因。 – Tyrandis

+0

我可以使用println,但我的老师希望我在印刷品中使用“,”,因此它将是printf,而不是println – Tyrandis

回答

1

这是不对的:

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。)

+0

还有一件事为什么它的输出看起来像 剩下的项目是: – Tyrandis

+0

为 System.out.printf(“剩下的项目是:\ n”,NumItemsLeftOver); – Tyrandis

+0

什么是用'NumItemsLeftOver'替换的格式说明符? – ajb

1

您可以使用%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第2行显示的值。

System.out.printf("Amount of Hampers Made: %d %n", NumHampersMade); 
System.out.printf("The Items Left Over is: %d %n", NumItemsLeftOver);