46.2k views
4 votes
Write a program to show whether a string's first character is letter or digit using java functions

Write a program to show whether a string's first character is letter or digit using-example-1
User Evis
by
8.8k points

1 Answer

5 votes

Here is an example of a Java program that uses the Character class's isLetter and isDigit methods to check whether the first character of a string is a letter or a digit:

import java.util.Scanner;

public class FirstCharCheck {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");

String input = scanner.nextLine();

// check if the first character is a letter

if (Character.isLetter(input.charAt(0))) {

System.out.println("The first character is a letter.");

} else if (Character.isDigit(input.charAt(0))) {

System.out.println("The first character is a digit.");

} else {

System.out.println("The first character is not a letter or digit.");

}

}

}

This program prompts the user to enter a string and then uses the charAt() method to retrieve the first character of the string. The isLetter and isDigit methods are used to check if the first character is a letter or a digit. If the first character is a letter, the program prints "The first character is a letter." If the first character is a digit, the program prints "The first character is a digit." If the first character is neither a letter nor a digit, the program prints "The first character is not a letter or digit."

You can also check whether the first character is a letter or a digit by using regular expressions, but using the Character class's isLetter and isDigit methods is a simpler and more efficient way to check the type of a character in Java. Been awhile since I have worked with Java is this fine.

User Michael GEDION
by
8.2k points