【发布时间】:2021-01-08 21:59:07
【问题描述】:
我正在尝试编写一个简单的程序,该程序要求用户输入由零和一组成的输入,并检查每个字符以查找双零“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”之后,我才能让程序打印“状态 C”+ 字符?也就是说,在程序找到 '00' 之后,它应该在状态 C 中保持 '00' 和它后面的所有其他字符。
【问题讨论】:
-
inputString.contains("00") ?