简体   繁体   English

Integer.toString(argument)或toString(argument)

[英]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 编号:1234 5678 9012 3456
Expiration date: 10/14 到期日: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). 我以为它会起作用(expiryYear本质上被声明为int类型的实例变量)。 I've consulted my book (The official Java Tutorial also found online), and can't seem to find anything. 我已经查阅了我的书(也可以在网上找到官方的Java教程),但似乎找不到任何东西。 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) 我什至不了解Integer.toString,一个朋友在尝试使用toString()之后告诉了我,所以如果有人还可以告诉我在哪里可以找到这些方法,我将不胜感激(我不要以为他们在我的书中)

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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