如何检查用户输入是否遵循正确的格式。

huangapple go评论72阅读模式
英文:

how to check if a user's input follows the correct format

问题

Sure, here's the translated code without the user input and only the translated parts:

public static void main(String[] args) {
    Scanner scan = null;
    String info = null;

    while (true) {
        scanner = new Scanner(System.in);
        info = scanner.nextLine();
        if (!info.contains("--") || !info.contains(" ")) {
            System.err.println("invalid format");
            continue;
        }

        String[] infoList = info.split("--");

        if (infoList.length != 3) {
            System.err.println("invalid format");
            continue;
        }

        String name = infoList[0].trim();
        String age = infoList[1].trim();
        String gender = infoList[2].trim();

        if (!age.matches("\\d+")) {
            System.err.println("age must be a number");
            continue;
        }
    }
}

This version of the code checks for the correct format, ensures there are exactly 3 inputs, and validates the age as a number. It's a more concise approach compared to listing every possible invalid condition separately.

英文:

I want to write a program to ask the user's age, gender, name. Are there any simpler methods which I can use to check if the input is following the correct format?

The correct format is: name -- age -- gender

For example, Bob -- 22 -- M

public static void main (String[] args){
      
       Scanner scan = null;
       String info = null;

       while (true){

            scanner = new Scanner (System.in);
            info = scanner.nextLine();
            if (!info.contains("--") || !info.contains(" ")){
                   System.err.println("invalid format");
                   continue;
             }
            
             String infoList = info.split("--");

             
             // I need to check if the input contains any other sign such as ~,! and if there are 
             // exactly 3 inputs
             // so the list should be {X,Y,Z}, I also need to check if the age is a number rather 
             //than a letter or a sign.
            
}

If I write my program like that (use if condition to check every possible invalid condition), which will make my program long-winded.

答案1

得分: 3

The translated code part:

最佳方法是使用正则表达式而不是将字符串拆分为数组并逐个检查每个项。

此正则表达式应该有效:

[A-Za-z]+ -- [0-9]{1,2} -- [MF]

然后,您可以检查任何字符串是否与此表达式匹配:

String regex = "[A-Za-z]+ -- [0-9]{1,2} -- [MF]";
String testString = "Bob -- 22 -- M";

if (testString.matches(regex)) {
    // testString matches the regex
} else {
    // testString doesn't match the regex
}

在检查表达式是否匹配之后,您可以拆分字符串并能够单独操作每个元素。请记住按照 " -- " 而不是 "--" 进行拆分,否则字符串中会有空格,这可能会在稍后处理数据时出现问题。

如果您想更好地理解正则表达式的工作原理,我建议您搜索一些相关内容,因为它可以非常有用。

英文:

Best way to do it would be using regular expressions rather than splitting the string into and array and checking each item indidually.

This regex should work:

[A-Za-z]+ -- [0-9]{1,2} -- [MF]

You can then check if any string matches this expression

String regex = "[A-Za-z]+ -- [0-9]{1,2} -- [MF]";
String testString = "Bob -- 22 -- M";

if(testString.matches(regex)) {
    // testString matches the regex
} else {
    // testString doesnt match the regex
}

After checking that the expression matches you could split the string and be able to manipualte each of the elements individually. Remeber to split by " -- " rather than "--" else you will get spaces in the string which can give problems later when manipulating the data.

If you want to understand better how regex works I would recommend you to search a bit about it as it can be very useful.

答案2

得分: 1

你可以使用正则表达式

String info = "Bob--22--M";

if (info.matches("[a-zA-z]+--[0-9]{2}--[MFmf]")){
    System.out.println("无效格式");
}

查看正则表达式这里

英文:

You can use Regex

String info = "Bob--22--M";

if (info.matches("[a-zA-z]+--[0-9]{2}--[MFmf]")){
    System.out.println("invalid format");
}

See regex here

答案3

得分: 1

Here's the translated content:

String[] infoList = info.split("--");
// infoList[0]应该是姓名,infoList[1]应该是年龄,infoList[2]应该是性别

if (!checkFormat(infoList[1], infoList[2])) {
   System.out.println("格式无效");
   return;
}

验证方法:

private boolean checkFormat(String age, String gender) {

  try {
      int aux = Integer.parseInt(age);  
  } catch(Exception) {
      return false;
  }
  if (!(gender.equals("M") || gender.equals("F"))) {
      return false;
  }
  return true;
}

关于姓名,除非有具体要求,我无法对其进行处理。

英文:

You can do a simple method for each verification and then only call that method.

String[] infoList = info.split("--");
// infoList[0]should be the name, infoList[1] should be the age and infoList[2] should be the gender

if(!checkFormat(infoList[1],infoList[2])){
   System.out.println("invalid format");
   return;
}

method for verification:

private boolean checkFormat(String age, String gender){

  try
  {
      int aux =Integer.parseInt("age");  
  }
  catch(Exception)
  {
      return false;
  }
  if(!(gender.Equals("M") || gender.Equals("F")))
  {
      return false;
  }
  return true;
}

About the name, unless you have some especification, I can't do nothing about it.

huangapple
  • 本文由 发表于 2020年8月10日 20:58:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/63340716.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定