1

I have two classes in a package: firstClass and secondClass.

I created a textfield in firstClass, let's assume it's txtStringNumber.

I created a method in firstClass to get txtStringNumber value, like this:

public String getStrNumber(){
    String strNumber = txtStringNumber.getText();
    return strNumber;
}

I must pass it to secondClass as String and put the strNumber as BigInteger value.

In second class I created a method to get value of txtStringNumber from firstClass, like tis:

public static String theNumbers(){
     firstClass f = new firstClass();

     return f.getStrNumber();
 }
public static String strAllNumbers = theNumbers();

When I print strAllNumbers in secondClass, it prints the correct value. Then I add this:

public static BigInteger bigAllNumbers = new BigInteger(strAllNumbers);

In my mind, it should works. But in real, it doesn't. Error occurs.

So I check the error, there said:

throw new NumberFormatException("Zero length BigInteger");

I guess BigInteger accept strAllNumbers as empty. But just like I already said, when I print strAllNumbers directly without set it to BigInteger, it returns the correct value.

What's wrong here and how can I fix this?

0

2 Answers 2

2

You're creating a firstClass object, f, and getting a String from its textfield before anybody ever has a chance to enter text in it. So no surprise that it's empty.

Solution: Don't do this! Only get the text after something that makes sense has been entered. I'm guessing that you have two firstClass objects, one displayed, and a second one created in this method, and are guilty of magical thinking that changes to the displayed object will be reflected in the newly created one, but that's not how programming works. Instead pass a valid reference of the displayed object to the other object that needs it.

1
2

You're creating a new instance of firstClass in the theNumbers method (firstClass f = new firstClass();), it's very unlikely the the value of the text field has been set to anything useful (especially by the user)

You either need to supply a means of firstClass to pass the value from the text field to secondClass, probably via a setter of some kind (this is classic producer-consumer pattern) or set up a mechanism for firstClass to notify secondClass when the value changes and then have secondClass retrieve that value (this is a class observer pattern).

In any case, you should not be creating a new instance of these classes, you need to create them and then pass these instance to which ever one is going to act as the controller...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.