如何格式化字符串输出,以使列均匀居中? [英] How to format string output, so that columns are evenly centered?

查看:159
本文介绍了如何格式化字符串输出,以使列均匀居中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的java课程中,我们写了一个卡片程序,你在其中选择一张秘密卡片,最后它会告诉你你的秘密卡是什么。我只有一个问题,那就是格式化输出。到目前为止,当它打印时,第一列是偶数,但第二列和第三列不是。我的老师说要使用空格,但我试过这个并不起作用。我知道有一种方法可以格式化它,但我不确定。输出如下所示:

In my java class we wrote a card program in which you choose a "secret card", and at the end it tells you what your secret card was. I am only having one issue, and that is formatting the output. As of right now, when it prints the fist column is even but the 2nd and 3rd are not. My teacher said to use spaces, but I have tried this and does not work. I know there is a way to format it but am unsure. The output looks like this:

     Column 0           Column 1           Column 2
    ________________________________________________
     3 of Spades    3 of Diamonds  Ace of Diamonds
     9 of Diamonds    2 of Diamonds   10 of Diamonds
   Ace of Spades   10 of Hearts King of Clubs
     6 of Clubs    4 of SpadesQueen of Hearts
     5 of Diamonds    2 of Hearts    7 of Clubs
     2 of Spades Jack of Diamonds    3 of Hearts
     5 of Hearts    4 of Hearts    7 of Diamonds

我的输出代码如下:

import java.util.Scanner;
import java.util.Random;

public class CardTrick {
  public static void main(String[] args) {

/* declare and initialize variables */
int column = 0, i = 0;
String name = " ";
String playAgain = " ";
String seeDeck = " ";

/* Declare a 52 element array of cards */
Card[] deck = new Card[52];

/* Declare a 7 by 3 array to receive the cards dealt to play the trick */
Card [][] play = new Card[7][3];

/* Declare a Scanner object for input */
Scanner input = new Scanner(System.in);

如果你想我可以发布整个代码,但我试图不发布很多。我非常感谢任何帮助,因为我是Java的新手。

If you want I can post the entire code, but I was trying not to post a lot. I greatly appreciate any help, being I am new to Java.

推荐答案

我也会使用格式建议,但是我的情况有点不同。

I'm also going with the "format" suggestion, but mine is a little different.

在你的程序中,你依赖的是你的卡的 toString 。因此,将其格式化为固定长度,然后您可以在任何地方使用它们,它们将占用相同的空间。

In your program, you're relying on your card's toString. So make that formatted in a fixed length, and then you can use them anywhere and they will take up the same space.

public String toString() {
    return String.format( "%5s of %-8s", rank, suit );
}

当你打印出来时,你的所有卡片都会对齐of部分,我认为这是你在第一个输出栏中的目的。

When you print this out, you'll have all your cards aligned on the "of" part, which I think is what you were going for in your first output column.

%5s部分右对齐字段中的等级5字符宽,并且%-8s部分左对齐8字符宽的字段(这意味着如果西装短于8个字符,右边还有其他空格)。

The "%5s" part right-aligns the rank in a field 5 characters wide, and the "%-8s" part left-aligns the suit in a field 8 characters wide (which means there are additional spaces to the right if the suit is shorter than 8 characters).

这篇关于如何格式化字符串输出,以使列均匀居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆