0

Every time I write Character.isLetter(4)) it highlights isLetter...

Please help. I am trying to make a program that you have to tell the age to continue, but if you enter letters, an error pops up.

this is my full code, and it doesn't work.

import java.util.Scanner; 
public class Prmtrs1
{
public static int user_age2;
public static String user_age;
public static void main(String args[]) {

Scanner input = new Scanner(System.in);
Prmtrs2 POblect = new Prmtrs2 ();

System.out.println("Type in your name in here! ");
String name = input.nextLine();

POblect.Hello(name);
System.out.println("");
System.out.println("Enter your age,  " + name);
user_age = input.nextLine();
while(user_age.matches("\\d+")) {
    System.out.println("enter numbers from 0 to 9");
    user_age = input.nextLine();
}
System.out.println("Your age is  " + user_age + ", "  + name);
int user_age2 = Integer.parseInt(user_age);
if(user_age2 >= 18)
{
    System.out.println("So...");
System.out.println("You are eligible to Vote, " + name + "!");
}
else{
    System.out.println("So...");
System.out.println("You are not eligible to vote, " + name + "!");
}
}
}
haces
  • 11
  • 4
  • *I am trying to make a program that you have to tell the age to continue* Then your code makes even less sense... show more of it. – Elliott Frisch Jun 23 '18 at 18:07
  • Can you please elaborate you question? – NullPointer Jun 23 '18 at 18:12
  • 1) *"this is my full code"* That code does not compile due to a reference to `Prmtrs2`. 2) But even if it did, entering an update as an answer is not the correct way to do things. Instead [edit] the question to include new code. – Andrew Thompson Jun 24 '18 at 01:28

1 Answers1

1

You probably meant to write Character.isLetter('4'), '4' is a char, while 4 is an int.

Character.isLetter expects a char or an int codePoint.

You should also consider using regex and doing s.matches("\\d+") (where s is your input string) to see if your string consists solely of digits. The matches function takes in a regular expression.

In the example I just showed you \d means "digit" and + means "one or more".

But if you want to use Character.isLetter this can be done like so:

for(char c : s.toCharArray()) {
    if (Character.isLetter(c)) {
        return false;
    }
}
Coder-Man
  • 2,391
  • 3
  • 11
  • 19
  • [`Character.isLetter(int)`](https://docs.oracle.com/javase/9/docs/api/java/lang/Character.html#isLetter-int-) is probably better than using `char`. In general, we shouldn't be operating on `char` directly unless we know something about the source data. Something like `s.codePoints().noneMatch(Character::isLetter)`. See e.g. https://stackoverflow.com/a/12280911/2891664. – Radiodef Jun 23 '18 at 18:23