Java 使用Integer.parseInt将字符串输入从JTextField转换为整数,但仍收到错误消息 textSeven是一个JTextField 我正在使用带有动作侦听器的提交按钮

Java 使用Integer.parseInt将字符串输入从JTextField转换为整数,但仍收到错误消息 textSeven是一个JTextField 我正在使用带有动作侦听器的提交按钮,java,swing,integer,jtextfield,Java,Swing,Integer,Jtextfield,代码: 如果您得到一个NumberFormatException,那么java无法将任何内容解析为数字 要检查的其他内容可能是空字符串“”或空字符串(在这种情况下,它可能引发空指针异常) 也许还可以检查是否有虚假的空白-用修剪来去除它,例如 //get favorite number String amountInput = textSeventh.getText(); if (amountInput == null) { System.err.println("amountInput

代码:


如果您得到一个NumberFormatException,那么java无法将任何内容解析为数字

要检查的其他内容可能是空字符串“”或空字符串(在这种情况下,它可能引发空指针异常)

也许还可以检查是否有虚假的空白-用修剪来去除它,例如

//get favorite number
String amountInput = textSeventh.getText();

if (amountInput == null) {
    System.err.println("amountInput was null, no point continuing");
    return;
}

// make it a bit more obvious if there's whitespace
System.out.println("amountInput = +++" + amountInput + "+++");

amountInput = amountInput.trim();

if (amountInput.equalsIgnoreCase("")) {
    System.err.println("There's nothing there!!");
}

int dollars = -1337;
try {
    dollars = Integer.parseInt(amountInput);
} catch (Exception e) {
    System.err.println("Error when parsing value.\n" + e);
    // optional
    // e.printStackTrace();
}
System.out.println(dollars);

@GSGIv您是否可以在此处添加错误..?您是在
ActionListener中执行此操作,还是在创建
JTextField
后立即调用它?1)为了更快地获得更好的帮助,请发布或。2) 为了用户的利益,为他们提供一个带有
SpinnerNumberModel
JSpinner
(而不是一个文本字段)。favoriteLetter=lastNameInput.toUpperCase().charAt(0)。。。System.out.println(“您最喜欢的字母是“+favoriteLetter+”);你看到这个System.out消息了吗?因为字符(0)看起来非常可疑。我猜这就是引发异常的原因。下面是错误消息的一部分:线程“AWT-EventQueue-0”java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0错误消息仍然存在,上面的编辑代码实际上是在哪一行获得错误消息的?你能把全部编辑好的代码贴在这里吗?还有一件事。StringIndexOutOfBoundsException表示您试图检索无效索引。在解析为整数之前检查字符串的长度。我正在尝试将整数或双精度值(如12)输入textField,然后将其从字符串转换为整数。
//get favorite number
String amountInput = textSeventh.getText();

if (amountInput == null) {
    System.err.println("amountInput was null, no point continuing");
    return;
}

// make it a bit more obvious if there's whitespace
System.out.println("amountInput = +++" + amountInput + "+++");

amountInput = amountInput.trim();

if (amountInput.equalsIgnoreCase("")) {
    System.err.println("There's nothing there!!");
}

int dollars = -1337;
try {
    dollars = Integer.parseInt(amountInput);
} catch (Exception e) {
    System.err.println("Error when parsing value.\n" + e);
    // optional
    // e.printStackTrace();
}
System.out.println(dollars);