如何在 Java 中编写一个程序来查找 '00' 检查字符串中的每个字符?

How to write a program in Java that looks for a '00' checking every character in a string?

我正在尝试编写一个简单的程序,要求用户输入由 0 和 1 组成的输入,并检查每个字符以查找双零“00”,如果当前字符是“1”则程序被认为处于状态“A”,因此它会打印状态和字符,如果字符为“0”,则程序处于状态“B”,如果有“00”,则程序处于状态“C” ,进入状态“C”后(找到'00'后)程序无法退出该状态,这意味着它将继续检查每个字符,但结果字符串应该是“状态C”+字符,即使字符是单个零或一个。

目前我有这样的东西

import java.util.Scanner;
    
public class onesandzeroes {
     public static void main(String[] args) {     
         System.out.println("Write a String that consists of 0 and 1");
           Scanner scanner = new Scanner(System. in);
           String inputString = scanner.nextLine();
           
           for (int index = 0; index < inputString.length();
index++) {
     char aChar = inputString.charAt(index);
     if (aChar == '0'){
         System.out.println("State B " + aChar);
         
         /* This is the part I'm having trouble with, I was thinking about something like
         
         if(aChar =='0' && charAt(index + 1 == '0')){
                 System.out.println("State C" + aChar + charAt(index + 1);
                 }
         to look for a '0' that is followed by another '0' but it doesn't work
         */
         
     } else{
         System.out.println("State A " + aChar);
     }
}
    }    
    
}

我知道您可能会查看整个字符串并只检查是否有“00”,但我想单独检查每个字符,除非它查找“00”

所以我有两个问题: 如何在字符串中查找“00”?理想的方法是检查每个“0”是否有后续的“0”。

如何让程序仅在找到第一个 '00' 后才打印“State C”+ 字符?也就是说,在程序找到 '00' 之后,它应该在状态 C 中等待 '00' 以及它后面的所有其他字符。

也许这样:

import java.util.Scanner;

public class StringScanner {

    public static void main(String[] args) {

        System.out.println("Write a String that consists of 0 and 1");

        final var scanner = new Scanner(System.in);

        final String inputString = scanner.nextLine();

        var currentState = State.A;

        for (int index = 0; index < inputString.length(); index++) {

            final char currentChar = inputString.charAt(index);

            System.out.println("The current char is " + currentChar + " and I'm in state " + currentState);

            if (currentState == State.C) {
                // do nothing because final state has already been reached
                continue;
            }

            if (currentState == State.B) {
                if (currentChar == '0') {
                    // 2 zeros found got into final state :)
                    currentState = State.C;
                } else {
                    //
                    currentState = State.A;
                }
                continue;
            }

            if (currentState == State.A) {
                if (currentChar == '0') {
                    currentState = State.B;
                }
            }
        }
    }

    private enum State {
        A, B, C
    }

}

首先你可以查看inputString.contains("00"); 如果为真写

inputString.charAt(inputString.indexOf("00") + 2);