我是Java编程的初学者,我尽我所能,但我似乎无法解决我的问题。
我遇到的问题是getCardID()
方法保持返回空值,getTokenBalance()
似乎工作正常,或者我需要特殊代码从getCardID()
返回字符串值吗? / p>
非常感谢任何帮助。
这是Prepaidcard.java
类:
class PrepaidCard {
private String cardID;
private int tokenBalance;
public PrepaidCard(String id) { // My First Constructor
String cardID = id ;
}
public PrepaidCard(String id, int token) { // My Second Constructor
String cardID = id;
tokenBalance = token;
}
public void addToken(int token) { // Methods
tokenBalance =token+tokenBalance;
}
public void deductToken(int token) { // Methods
tokenBalance=tokenBalance-token;
}
public int getTokenBalance() { // Methods
return tokenBalance;
}
public String getCardID() { // Why does this method keep returning null value?
return cardID;
}
}
这是用于测试prepaidcard.java
import java.util.*;
class testprepaid {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Insert card1 id : ");
String newid = sc.nextLine(); // my scanner class that read user input in String
System.out.print("Insert card2 id : ");
String newid2 = sc.nextLine(); // my scanner class that read user input in String
System.out.print("Enter Card2 initial token : ");
int itoken = sc.nextInt();
PrepaidCard card1 = new PrepaidCard(newid); // object created base on 1st & 2nd Constructor
PrepaidCard card2 = new PrepaidCard(newid2,itoken);
System.out.println("Card1 ID: " + card1.getCardID()); // the method return null when called
System.out.println("Card1 token balance : " + card1.getTokenBalance());
System.out.println("Card2 ID: " + card2.getCardID()); // and this
System.out.println("Card2 token balance : " + card2.getTokenBalance());
其他行没有错误,所以我没有添加它们。
您可以看到我的运行时错误here。
答案 0 :(得分:5)
在构造函数中,您声明了一个新的局部变量:
public PrepaidCard(String id, int token) {// My Second Constructor
String cardID = id; //This should be cardID = id;
tokenBalance = token;
}
根据您的IDE,您可以启用可以告诉您未初始化私人成员的警告。
答案 1 :(得分:2)
String cardID = id ;
应该是一个实例变量。
因此删除字符串cardID
-
public PrepaidCard(String id){ //My First Constructor
cardID = id ;
}