【问题标题】:isLetter Method isn't working in JavaisLetter 方法在 Java 中不起作用
【发布时间】:2018-06-23 17:56:08
【问题描述】:

每次写Character.isLetter(4)) 它突出显示isLetter...

请帮忙。我正在尝试制作一个程序,您必须告诉年龄才能继续,但是如果您输入字母,则会弹出错误。

这是我的完整代码,它不起作用。

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

【问题讨论】:

  • 我正在尝试制作一个程序,你必须告诉年龄才能继续然后你的代码就更没有意义了......显示更多。
  • 你能详细说明你的问题吗?
  • 1) “这是我的完整代码” 由于引用了Prmtrs2,该代码无法编译。 2)但即使这样做,输入更新作为答案也不是正确的做事方式。而是edit 包含新代码的问题。

标签: java


【解决方案1】:

您可能打算写Character.isLetter('4')'4'char,而4int

Character.isLetter 需要 charint 代码点。

您还应该考虑使用正则表达式并执行s.matches("\\d+")(其中s 是您的输入字符串)来查看您的字符串是否仅由数字组成。 matches 函数接受一个正则表达式。

在我刚刚向您展示的示例中,\d 表示“数字”,+ 表示“一个或多个”。

但如果你想使用Character.isLetter,可以这样做:

for(char c : s.toCharArray()) {
    if (Character.isLetter(c)) {
        return false;
    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-09
  • 2016-04-15
  • 2011-03-30
  • 1970-01-01
相关资源
最近更新 更多