格式化输出方法

时间:2012-11-18 04:58:53

标签: java object format

我对display array方法有疑问。我无法想象如何格式化它:

Credit Card # 4: 
8908 9014 8812 1331

我需要做的是为每个数组元素调用display方法并在字符串中为标签传递数组的索引,我只是想弄清楚如何做到这一点,我试过这个但是错了:< / p>

System.out.println(display("Credit Card # %d", cred1[i]));

有人可以建议一种方法吗?

package homework4;
import java.util.Scanner;
public class Prog4 {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args)
{   CreditCardNumber[] cred1;
    CreditCardNumber cred2 = getInput();
    Display("The complete number from your input:", cred2);
    cred1 = getInputArray();
    DisplayArray(cred1);
    TryAnother();
}

public static CreditCardNumber getInput() {
    String ID;
    String accNum;
    CreditCardNumber tempCred;      
    System.out.printf("Please enter issuer ID:");
    ID = scanner.next();
    System.out.printf("Please enter account number:");
    accNum = scanner.next();
    tempCred = new CreditCardNumber(ID, accNum);

    return tempCred;
}
public static void Display(String ch, CreditCardNumber cred2)
{

    System.out.println(ch);
    System.out.println(cred2.toString().replaceAll(".{4}", "$0   "));       
}

public static CreditCardNumber[] getInputArray()
{
    CreditCardNumber[] tempArray;
    String tempID;
    int size;       
    System.out.printf("Please enter size of the aray:");
    size = scanner.nextInt();
    if(size < 1)
    {
        size = 1;
    }
    tempArray = new CreditCardNumber[size];
    System.out.printf("Please enter issuer ID:");
    tempID = scanner.next();
    System.out.print(tempArray.length);
    for(int i = 0; i < tempArray.length; i++)
    {
        tempArray[i] = new CreditCardNumber();
        tempArray[i].CreateCred(tempID);
    }

    return tempArray;
}

public static void DisplayArray(CreditCardNumber[] cred1)
{
    for(int i = 0; i< cred1.length; i++)
    {
        System.out.println(display("Credit Card # %d", cred1[i]));
    }
}

public static boolean TryAnother()
{
    String s;
    System.out.printf("Get more credit card numbers? (n for no):");
    s = scanner.next();
    if(s.charAt(0) != 'N' && s.charAt(0) != 'n')
    {
        return true;
    }
    return false;
}
}

2 个答案:

答案 0 :(得分:1)

听起来你需要的只是一个新的线条角色。例如。

System.out.println("Credit Card # " + cred1[i] + "\n" + cred2.toString());

新行字符“\ n”会将输出删除到它自己的行上。

答案 1 :(得分:0)

这样做:

System.out.format("Credit Card # %d:\n%s", i, cred1[i].toString());