简体   繁体   中英

Integer.toString(argument) or toString(argument)

I've written up some code for a Credit card class, pasted below. I have a constructor that takes in the said variables, and am working on some methods to format these variable's into strings such that the end output will be something along the lines of

Number: 1234 5678 9012 3456
Expiration date: 10/14
Account holder: Bob Jones
Is valid: true

(Won't format correctly - I'm unsure how to do it, would be greatful of someone can edit for me :) )

My question is, in the line

String shortYear = Integer.toString(expiryYear).substring(2,4);

Why won't the following work:

toString(argument).substring(2,4) 

I would have imagined it wound have worked (expiryYear is essentially declared as an instance variable of type int). I've consulted my book (The official Java Tutorial also found online), and can't seem to find anything. I didn't even know about Integer.toString, a friend told me about that after trying to play with toString(), so it would be even more greatly appreciated if someone could also tell me where I can find these sorts of methods (I don't think they're in my book)

public class CreditCard {

    private int expiryMonth;
    private int expiryYear;
    private String firstName;
    private String lastName;
    private String ccNumber;

    public CreditCard(int expiryMonth, int expiryYear, String firstName, String lastName, String ccNumber) {
        this.expiryMonth = expiryMonth;
        this.expiryYear = expiryYear;
        this.firstName = firstName;
        this.lastName = lastName;
        this.ccNumber = ccNumber;
    }

    public String formatExpiryDate() {
        String shortYear = Integer.toString(expiryYear).substring(2, 4);
        String expiryDate = expiryMonth + "/" + shortYear;
        return expiryDate;
    }

    public static void main(String[] args) {
        CreditCard cc1 = new CreditCard(10, 2014, "Bob", "Jones", "1234567890123456");

        System.out.print(cc1.formatExpiryDate());
    }
}

试试String.valueOf(expiryYear).substring(2,4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM