【问题标题】:Correcting alignment while printing in java [duplicate]在java中打印时更正对齐[重复]
【发布时间】:2017-06-27 18:37:44
【问题描述】:

我制作了一个具有以下 sn-p 的 switch-case Restaurant 程序:

for(int r=0;r<=17;r++)
{
    while(qty[r]>0)
    {
        System.out.println(qty[r]+" X "+O[r]+"              "+l[r]);
        break;
    }
}
//qty has the quantity(int) ; O has the Item name (String) and l has the cost (int)

由于字符串长度不同,输出不统一——没有正确对齐。

输出:

*********************************************************
*********************************************************
**************************BILL***************************

Thu Feb 09 22:01:36 IST 2017

Your phone number - 9821809843
Bill number is 4180536
You have ordered :
Item Name with quantity            Price
1 X Fried Raviolli              400
1 X Potato Fries with Jalapeno and Cheese Dip              800

The total bill amount is Rs.1200

Hope you enjoyed. Visit us again soon!

关于如何纠正此问题的任何想法?

【问题讨论】:

  • @nhouser9 是的,这在一定程度上解决了我的问题。但由于我是新手,我不确定如何编辑我的 sn-p。请帮我一个忙,告诉我怎么做。提前致谢!
  • 好的,我在下面发布了答案。如果有帮助,请记得点赞并接受。

标签: java arrays printing alignment


【解决方案1】:

将您的打印语句替换为以下内容:

System.out.printf("%d X %-50s %d", qty[r], O[r], l[r]);

以下是有关此方法的一些文档:http://web.cerritos.edu/jwilson/SitePages/java_language_resources/Java_printf_method_quick_reference.pdf

附带说明,请描述性地命名您的变量。如果您养成命名数组lO 的习惯,您会发现编写任何更难的项目几乎是不可能的。评论

//qty has the quantity(int) O has the Item name (String) and l has the cost (int)

应该没有必要,数组应该命名为qtynamecost。更好的做法是创建一个对象来存储所有这三个字段。

【讨论】:

  • 这里的%是干什么用的?
  • 这段代码可以编译吗?
  • @LinuxGeek 在我的回答中添加一些文档以解决您的评论
  • 不是!我在 O[r] 之前的 + 处得到第一个错误,然后在执行时得到第一个错误
  • @LinuxGeek 它应该被修复,我只是在错误的地方有一个 + 号。在我的机器上测试,它工作正常。查看编辑后的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
  • 1970-01-01
  • 2013-10-29
相关资源
最近更新 更多