有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java输入字母

我正在做一个java活动,如果名称以字母A-G开头,以字母H-z结尾,那么输出无效。下面是我的代码:

System.out.print("Enter your name: ");
String str = in.readLine();
 if(str.startsWith("a" )){
            System.out.print("INVALID!");
        }  if(str.endsWith("h")){
            System.out.print("INVALID!");
        }

这是可行的,但如何实现字母a到g和h到z 我已经试过这个[a-g],但它不起作用


共 (2) 个答案

  1. # 1 楼答案

    您也可以考虑在^ {A1}方法中使用正则表达式。比如:

    string.matches("^[A-Ga-g].*.[H-Zh-z]") //Where string is a variable in here
    

    注意:这个正则表达式将返回给定字符串是否以A-G开头(大写/小写)和以H-Z结尾(大写/小写)。因此,在执行验证时,您可能想要否定它。比如:

    if(!string.matches("^[A-Ga-g].*.[H-Zh-z]")){
     //Signifies that the input does not start with A-G and ends with H-Z
    }
    
  2. # 2 楼答案

    看看^{}^{}。这两种字符串方法对这项任务都是非常宝贵的