简体   繁体   中英

Beginner java What is the error and why?

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");

ageTxt.getText() returns a java.lang.String . You are trying to assign that to an primitive int That will not work.

You can use Integer.parseInt() to convert a String to an int . But note that this might throw a NumberFormatException when the string is not a valid number. So you might want to wrap it in a try-catch block.

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");

Your question is not formulated quite well, but from what I can see you are trying to initialize int value with the method that returns String.

int age = ageTxt.getText( );

Instead, you should do:

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

And of course make sure parseInt doesn't throw an exception.

Hope so this will help you, as you are not casting the it to integer, getText() return a string that is why it gives you exception. First convert it into int like this and then use it.

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");
}

ageTxt.getText() returns a String object containing the characters typed by the user, and you try to put it in a int var, which can only contain integers. So it can't work. Just put it in a String object, then parse it to get the integer value by doing Integer.parseInt(myStringObject) . Be careful this can throw an exception if the String object doesn't contains an integer number.

you could use a scanner instead of having a jtextfield. here is the code i made :

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");
}


}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM