如何从自定义toString方法访问构造函数中的变量?

时间:2015-04-27 00:19:06

标签: java tostring

在我的例子中,我很难弄清楚如何将CreditCard构造函数中的字符返回到toString。

构造函数中的

char c将用于完成下面的说明,但出于某种原因,我无法在toString()中访问它。这是为什么?

//Write a class that represents a credit card. Call this class CreditCard.          
//The class will have the following fields and methods:
//A constructor which takes a String to set the card number. 
//Ignore dashes,spaces, and any other non-digit characters.
//A public method called toString that returns the credit card number.

public class CreditCard 
{
public CreditCard(String cardNumber)
{ 
        char c = 0;
        for( int i=0; i<cardNumber.length(); i++)
        {
            c = cardNumber.charAt(i);

            if(Character.isDigit(c))
            {
                System.out.print(c);
            }      
        }

}
public String toString() //toString method
{

        return c;
}

}//end code

2 个答案:

答案 0 :(得分:2)

java中有三种类型的变量(常用):

  • 局部变量在构造函数和方法中声明,并且仅在这些构造函数和方法中可用。您示例中的char c是一个这样的局部变量,只能在构造函数中访问。

  • 实例变量在构造函数和方法之外声明,但在类中。对于给定的类实例,它们可用于所有方法和构造函数。在您的情况下 - 给定的信用卡。

  • 静态变量的声明方式与实例变量相同,但具有static标记。这些可用于类的每个实例的方法和构造函数。在您的情况下,您创建的所有信用卡都可以使用静态变量。

您需要使用实例变量,以便将信用卡号从构造函数传输到toString方法。

public class CreditCard {
    String cardNumber = ""; // <-- This is an instance variable
    public CreditCard(String constructorInput) { // <-- Constructor input has the number as well as special characters, but it's just a local variable
        // Remove special characters (dashes and spaces) from
        // constructorInput here, and put the remaining numbers
        // in the instance variable - cardNumber.
    }

    @Override // <-- See the answers below for why I have this
    public String toString() {
        return cardNumber; // <-- Both the constructor and toString can access cardNumber, so just output it.
    }
}

进一步阅读:http://www.tutorialspoint.com/java/java_variable_types.htm

答案 1 :(得分:0)

保留StringBuilder字段,append字符和return字符toString()(我个人更喜欢for-each loop String.toCharArray() 3}})。像

这样的东西
public class CreditCard {
    // To store the digit(s) of the CreditCard String.
    private StringBuilder sb = new StringBuilder();

    // To construct a CreditCard instance.
    public CreditCard(String cardNumber) {
        // for-each char c in the character array backing
        // cardNumber.
        for (char c : cardNumber.toCharArray()) {
            // Test that the current character is a digit, 
            if (Character.isDigit(c)) {
                // It is, append it to the StringBuilder.
                sb.append(c);
            }
        }
    }

    @Override
    public String toString() {
        // Call toString() on the StringBuilder.
        return sb.toString();
    }
}

此外,最好利用Override annotationJLS-9.6.3.4 @Override表示(部分)程序员偶尔会在方法声明覆盖时重载 ... 如果使用注释@Override注释方法声明,但该方法不会覆盖或实现在超类型中声明的方法,或者不覆盖等效于{{1 public的方法,发生编译时错误。