-2

I have the following number: 43215 putted in a textField. and i got that number with the following instruction:

String cardNumber = jTextFieldCardNumber.getText();

I got a string value, how could I do to get the first number of that string?

the output should be : "4".

2
  • 2
    cardNumber.substring(0, 1)
    – Andreas
    Apr 30, 2020 at 0:10
  • 2
    You can use String#charAt() or String#substring Both are documented in the JavaDocs for the Java API.
    – WJS
    Apr 30, 2020 at 0:12

1 Answer 1

3

since your input is a string, you can use charAt which is defined at the String class. example:

    String cardNumber = "43215";
    if (cardNumber != null && cardNumber.length() > 0) {
      char firstChar = cardNumber.charAt(0);
      System.out.println("first char is: " + firstChar);
    } else {
        System.out.println("empty card number");
    }

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html

0

Your Answer

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

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