简体   繁体   English

检查字符串中的每个字符是否有效

[英]Check whether each character in string is valid

I am trying to create a method in java that would tell whether string is well formed. 我正在尝试在Java中创建一个方法来判断字符串是否格式正确。 Each character in a string should be equal to one of the pre-defined characters and nothing else. 字符串中的每个字符应等于预定义字符之一,而不能等于其他任何字符。 First character should be equal to one of the values in first array. 第一个字符应等于第一个数组中的值之一。 Second character should be equal to one of the values in columns array. 第二个字符应等于columns数组中的值之一。 Third character should be equal to one of the values in rows array. 第三个字符应等于rows数组中的值之一。 Fourth character should be equal to one of the values in fourth array. 第四个字符应等于第四个数组中的值之一。 I have this code so far. 到目前为止,我已经有了这段代码。

public static boolean formedGoodOrNot(String input) {
    char[] first = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'};
    int[] columns = {1, 2, 3, 4, 5, 6, 7, 8};
    char[] rows = {'A', 'B', 'C', 'D'};
    int[] fourth = {0, 1, 2, 3, 4, 5, 6, 7};
    if(input.length()==4) {
      for (int j = 0; j < first.length+1; ) {
        for (int k = 0; k < columns.length+1; ) {
          for (int l = 0; l < rows.length+1; ) {
            for (int m = 0; m < fourth.length+1; ) {
              if (input.charAt(0) == first[j]) {
                if (input.charAt(1) == columns[k]) {
                  if (input.charAt(2) == rows[l]) {
                    if (input.charAt(3) == fourth[m]) {
                      return true;
                    } else{
                      m++;
                    }
                  } else {
                    l++;
                  }
                } else{
                  k++;
                }
              } else{
                j++;
              }
            }
          }
        }
      }
    } else{
      return false;
    }
    return false;
  }

However, it gives me an error 但是,这给了我一个错误

java.lang.ArrayIndexOutOfBoundsException: 12 java.lang.ArrayIndexOutOfBoundsException:12

What is wrong here? 怎么了

Thank you 谢谢

You've used nested for loops which is not necessary for your problem. 您已使用嵌套的for循环,这对于您的问题不是必需的。 And also array.length + 1 is causing the exception to throw. 而且array.length + 1也会引发异常。 It should be array.length . 它应该是array.length

        char[] first = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'};
        int[] columns = {1, 2, 3, 4, 5, 6, 7, 8};
        char[] rows = {'A', 'B', 'C', 'D'};
        int[] fourth = {0, 1, 2, 3, 4, 5, 6, 7};

        boolean firstTest;
        boolean columnTest;
        boolean rowsTest;
        boolean fourthTest;

        if(input.length()==4) {
          for (int j = 0; j < first.length; j++){
               if (input.charAt(0) == first[j]){
                   firstTest = true;
                   break;
               }
           }
           if(!firstTest)
                 return false;

           for (int j = 0; j < columns.length; j++){
               if (input.charAt(0) == columns[j]){
                   columnsTest= true;
                   break;
               }
           }

           if(!columnTest)
                 return false;

          // Do the same for other tests as well


          // if all tests are passed
          return true;
}

If you want a quicker method, you can use a Hashset and save the time for looping. 如果您想要一种更快的方法,则可以使用哈希集并节省循环时间。

Set<Character> first= new HashSet<>(Arrays.asList('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'));

Set<Integer> columns= new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8));

// create other sets

if(first.contains(input.charAt(0)) && columns.contains(input.charAt(1)) && /*other similar checks*/)
    return true;
return false;

All of your index checks should be 您所有的索引检查都应

< first.length; 

not

< first.length+1; 

etc... 等等...

For example, your first array is 0..11 and your are accessing 12. 例如,您的第一个数组是0..11,而您正在访问12。

BTW Welcome to Stack Overflow! 顺便说一句,欢迎来到堆栈溢出!

public static boolean formedGoodOrNot(String input) {
    char[] first = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'};
    int[] columns = {1, 2, 3, 4, 5, 6, 7, 8};
    char[] rows = {'A', 'B', 'C', 'D'};
    int[] fourth = {0, 1, 2, 3, 4, 5, 6, 7};
    if(input.length()==4) {
      for (int j = 0; j < first.length; ) {
        for (int k = 0; k < columns.length; ) {
          for (int l = 0; l < rows.length; ) {
            for (int m = 0; m < fourth.length; ) {
              if (input.charAt(0) == first[j]) {
                if (input.charAt(1) == columns[k]) {
                  if (input.charAt(2) == rows[l]) {
                    if (input.charAt(3) == fourth[m]) {
                      return true;
                    } else{
                      m++;
                    }
                  } else {
                    l++;
                  }
                } else{
                  k++;
                }
              } else{
                j++;
              }
            }
          }
        }
      }
    } else{
      return false;
    }
    return false;
  }

REGEX 正则表达式

You should use regex for this purpose! 您应该为此使用正则表达式! The regex matching this pattern is : 匹配此模式的正则表达式为:

^[al][1-8][AD][0-7]$

Now you just gotta plug this into a function : 现在,您只需将其插入功能即可:

 private static final Pattern PATTERN = Pattern.compile("^[a-l][1-8][A-D][0-7]$");


 public boolean formedGoodOrNot(String input) {
     return PATTERN.matcher(input).matches();
 }

and there you go, much more readable and short than your implementation! 这样一来,比您的实现更具可读性和简短性!

Edit 编辑

To understand how this regex works, please check out this link that explains it : https://regex101.com/r/SDlnzi/1/ 要了解此正则表达式的工作原理,请查看对此链接进行解释的链接: https : //regex101.com/r/SDlnzi/1/

Since your question is What is wrong here? 由于您的问题是这里什么问题? , let's have a look: , 我们来看一下:

  1. Your loops are nested before you check each character, causing unnecessary checks. 在检查每个字符之前,您的循环是嵌套的,从而导致不必要的检查。 Hint: You don't need to enter the loops for the 2nd, 3rd or 4th character when the 1st isn't valid. 提示:如果第一个字符无效,则无需输入第二个,第三个或第四个字符的循环。

  2. Two of those arrays contain int s, not char s, yet you simply compare the char s in the String with the int values, which doesn't work. 这些数组中的两个包含int ,而不是char ,但是您只是将Stringcharint值进行比较,这是行不通的。

  3. You compare your counters with length+1 instead of length , thus going out of bounds. 您将计数器与length+1而不是length ,因此超出范围。 (The length of those arrays isn't length+1 , it's length .) (这些数组的长度不是length+1 ,而是length 。)

  4. You have an infinite loop for any invalid String that starts with at least one valid character, as you only increment the counter in the else branch, but have no break / return condition for a partially invalid String . 对于任何以至少一个有效字符开头的无效String ,您都有一个无限循环,因为您仅在else分支中递增计数器,但对于部分无效的String没有break / return条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM