I'm a beginner in Java programming, I tried everything I could but I cant seems to troubleshoot my problem.
The problem Im facing is the getCardID()
methods keep returning null value, the getTokenBalance()
seems to work fine, or do i need special code to return a string value from getCardID()
?
Any help is very much appreciate.
This is Prepaidcard.java
class:
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;
}
}
This is the class use to test 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());
And other line contains no error so I didn't add them.
You can see my runtime error here.
In your constructor, you declared a new local variable:
public PrepaidCard(String id, int token) {// My Second Constructor
String cardID = id; //This should be cardID = id;
tokenBalance = token;
}
Depending on your IDE, you may enable warnings that could tell you about uninitialized private members.
String cardID = id ;
should be a instance variable.
So remove local declaration of String cardID
-
public PrepaidCard(String id){ //My First Constructor
cardID = id ;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With