2

我对显示数组方法有疑问。我不知道如何使它格式化:

Credit Card # 4: 
8908 9014 8812 1331

我需要做的是为每个数组元素调用 display 方法并在标签的字符串中传递数组的索引,我只是不知道该怎么做,我试过了,但它是错误的:

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;
}
}
4

2 回答 2

1

听起来你只需要一个换行符。例如。

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

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

于 2012-11-18T05:12:03.060 回答
0

做这个:

System.out.format("Credit Card # %d:\n%s", i, cred1[i].toString());
于 2012-11-18T05:18:17.190 回答