【问题标题】:How would I write a statement that will loop continuously as long as an array contains a certain value in JAVA只要数组在JAVA中包含某个值,我将如何编写一个将连续循环的语句
【发布时间】:2018-11-14 23:49:31
【问题描述】:

只要数组包含某个值,我将如何编写一个将连续循环的语句?只要数组包含特定字符,我就需要它继续循环,但如果数组不包含这些字符值,则停止循环。

我在下面有点这个,但我几乎 100% 肯定它不会工作

for(int PieceChecker = 0, PieceChecker < 1){

        //Code that needs to be carried out

        if (Arrays.asList(board).contains(♖)){
        PieceChecker++;
        }
    }

【问题讨论】:

  • 数组类型是什么?
  • @shmosel 它的字符数组
  • while (new String(board).indexOf('♖') &gt; -1) { ... }
  • @shmosel 对于多个条件,我只会使用 && 和 ||,对吗?

标签: java arrays loops for-loop chess


【解决方案1】:

使用字符串比使用列表更容易处理此类仅涉及字符的情况。使用无限的for 循环,一旦发现其中没有该字符,就退出它。为此,您可以使用indexOf

这里是可能对你有帮助的代码 sn-p:

String board_string = new String(board);
for(;;) {
    if(board_string.indexOf('♖') == -1) {
        System.out.println("Breaking out of loop...");
        break;
    }
    else {
    //do something here
    }
}

【讨论】:

    【解决方案2】:

    从问题中不清楚您是否要循环简单的字符数组或字符数组列表。 在这里,我想出了一些可能会有所帮助的东西。

    private static char[] myCharArray = new char[] { '\u00A9', '\u00AE', '\u00DD', 'A', 'B' };
    private static Logger _log = Logger.getLogger(Test.class.getCanonicalName());
    
    
    public static void main(String[] args) {
    
        // 1. Using character array directly
        for (int i = 0; i < myCharArray.length; i++) {
            while (myCharArray[i] == '\u00A9') {
                _log.info("Inside char array as this condition holds true");
            }
        }
    
        // 2. List of char arrays.
        List<char[]> list = Arrays.asList(myCharArray);
        for (char[] cs : list) {
            for (char c : cs) {
                while(c =='A'){
                    _log.info("Inside charToList array as this condition holds true");  
                }
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      只需使用while 循环。基本结构可以是

      while (true) {
          // test situation
          if (!goodSituation()) {
              break;
          }
          // do something here
      }
      

      【讨论】:

      • 没有问题,先生。顺便问一下,goodSituation() 函数是什么?
      • 它只是一个 stub 用于一些 OP 可能想要顶级实现的代码
      【解决方案4】:
      while (Arrays.asList(board).contains("♖")) {
          //do something
      }
      

      编辑基于@shmosel的评论:-

      对于像int[] 这样的原始数组,您可以在while 条件中使用类似的东西:-

      IntStream.of(a).anyMatch(x -> x == 2)
      

      对于一个原始的char 数组,你可以使用这个条件:-

      new String(cArr).indexOf('♖') > -1
      

      【讨论】:

      • @shmosel 为什么不呢?
      • @shmosel 那部分取自OP的代码,我只是展示while循环的使用
      • OP 的代码显然是错误的。它甚至没有引号。
      • @shmosel 我的代码可能在某处出错了?,我刚刚开始 CS 并且非常糟糕
      • 仍然不适用于 char 数组。而"♖" 不是字符。
      猜你喜欢
      • 1970-01-01
      • 2019-03-23
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 2016-04-27
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      相关资源
      最近更新 更多