【问题标题】:java get value from JTextField and set it as BigIntegerjava 从 JTextField 获取值并将其设置为 BigInteger
【发布时间】:2014-05-17 03:11:35
【问题描述】:

我在一个包中有两个类:firstClass 和 secondClass。

我在 firstClass 中创建了一个文本字段,假设它是 txtStringNumber。

我在 firstClass 中创建了一个获取 txtStringNumber 值的方法,如下所示:

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

我必须将它作为 String 传递给 secondClass 并将 strNumber 作为 BigInteger 值。

在第二类中,我创建了一个从 firstClass 中获取 txtStringNumber 值的方法,例如 tis:

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

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

当我在 secondClass 中打印 strAllNumbers 时,它会打印正确的值。然后我添加这个:

public static BigInteger bigAllNumbers = new BigInteger(strAllNumbers);

在我看来,它应该有效。但实际上,它没有。发生错误。

所以我检查了错误,那里说:

throw new NumberFormatException("Zero length BigInteger");

我猜 BigInteger 接受 strAllNumbers 为空。 但是就像我已经说过的,当我直接打印 strAllNumbers 而不将其设置为 BigInteger 时,它会返回正确的值。

这里出了什么问题,我该如何解决?

【问题讨论】:

    标签: java biginteger


    【解决方案1】:

    您正在创建一个 firstClass 对象 f,并在任何人有机会在其中输入文本之前从其文本字段中获取一个字符串。所以它是空的也就不足为奇了。

    解决方案:不要这样做!只有在输入有意义的内容后才能获取文本。 我猜你有两个 firstClass 对象,一个是显示的,另一个是在这个方法中创建的,并且有一种神奇的想法,即对显示对象的更改将反映在新创建的对象中,但这不是编程的工作方式.而是将显示对象的有效引用传递给需要它的其他对象。

    【讨论】:

    • @MadProgrammer:确实。还有一个 1+!
    【解决方案2】:

    您正在 theNumbers 方法 (firstClass f = new firstClass();) 中创建 firstClass 的新实例,文本字段的值不太可能设置为任何有用的值(尤其是用户)

    您要么需要提供firstClass 的方法将值从文本字段传递到secondClass,可能通过某种设置器(这是经典的producer-consumer pattern)或为@987654328 设置机制@ 在值更改时通知 secondClass,然后让 secondClass 检索该值(这是一个类 observer pattern)。

    在任何情况下,您都不应该创建这些类的新实例,您需要创建它们,然后将这些实例传递给任何一个将充当控制器的实例...

    【讨论】:

      猜你喜欢
      • 2017-11-26
      • 1970-01-01
      • 2012-06-12
      • 2012-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多