初学java是什么错误,为什么?

时间:2012-08-15 10:04:29

标签: java swing

JTextField ageTxt;
ageTxt = new JTextField("30");
int age = ageTxt.getText( );

if (age < 30)
    System.out.println("You are young");
else
    System.out.println("You are NOT young");

6 个答案:

答案 0 :(得分:5)

ageTxt.getText()返回java.lang.String。您正试图将其分配给原始int这将无效。

您可以使用Integer.parseInt()将String转换为int。但请注意,当字符串不是有效数字时,这可能会抛出NumberFormatException。所以你可能想把它包装在try-catch块中。

答案 1 :(得分:1)

JTextField ageTxt;
ageTxt = new JTextField("30");
String age = ageTxt.getText( );

if (Integer.parseInt(age) < 30)
    System.out.println("You are young");
else
    System.out.println("You are NOT young");

答案 2 :(得分:1)

您的问题配置得不是很好,但从我可以看到您尝试使用返回String的方法初始化int值。

int age = ageTxt.getText( );

相反,你应该这样做:

String ageS = ageTxt.getText();
int age = Integer.parseInt(ageS);
if (age < 30) {
  // do something
}

当然要确保parseInt不会抛出异常。

答案 3 :(得分:1)

希望所以这对你有所帮助,因为你没有将它转换为整数,getText()返回一个字符串,这就是为什么它会给你异常。首先将它转换为int,然后使用它。

JTextField ageTxt;
ageTxt = new JTextField("30");
int age = Integer.parseInt(ageTxt.getText( ));

if (age < 30){
    System.out.println("You are young");
}
else{
    System.out.println("You are NOT young");
}

答案 4 :(得分:0)

ageTxt.getText()返回一个包含用户输入的字符的String对象,并尝试将其放在int var中,该变量只能包含整数。所以它无法奏效。只需将其放在String对象中,然后通过执行Integer.parseInt(myStringObject)解析它以获取整数值。请注意,如果String对象不包含整数,则会抛出异常。

答案 5 :(得分:0)

您可以使用扫描仪而不是使用jtextfield。这是我做的代码:

import java.util.Scanner;

public class Test {
public static void main(String[]args){
int age;
Scanner getage = new Scanner(System.in);
System.out.println("How old are you");
age = getage.nextInt();
if (age < 30){
System.out.println("You are young");
}
else{
System.out.println("You are NOT young");
}


}
}