0

我正在尝试编写一个 java 程序,它将一个字符串作为输入并检查它是否有效。决定的规则是:

1)字符串是可识别的当且仅当它包含单词“pi”,“ka”,“chu”作为其片段,以任何顺序重复任意次数。2)如果它包含任何其他片段(或子序列),那么它是无法识别的

对于 ex-“皮卡丘”仅由“pi”、“ka”、“chu”组成,因此它是可识别的。“kachupi”仅由“ka”、“chu”、“pi”组成,因此可识别。“pipi”也是可识别的”,因为它包含两次“pi”。“pich”不可识别,因为有“ch”不是指定的子序列之一。

我在下面发布我的java代码。但它不能正常工作。请检查并帮助。提前致谢!

import java.util.Scanner;

public class RecognisingWords {


    public static void main(String[] args) throws Exception 
    {

        Scanner inp= new Scanner(System.in);
        String str;
        int len;
        System.out.println("Enter the string to be tested:");
        str=inp.nextLine();
        System.out.println(str);

        while(str !=null)
        {

        if(str.startsWith("pi"))
        {
            len=str.length();
            str= str.substring(2,len);          
        }

        else if(str.startsWith("ka"))
        {
            len=str.length();
            str= str.substring(2,len);          
        }

        if(str.startsWith("chu"))
        {
            len=str.length();
            str= str.substring(3,len);          
        }

        else
        {
            System.out.println("Unrecognisable Sequence");
            break;
        }

        }

        if(str == null)
        {
            System.out.println("Recognisable Sequence");
        }


    }

}
4

1 回答 1

2

您需要进行两项更改:

一、改变

if(str.startsWith("chu"))

else if (str.startsWith("chu"))

否则像“pipi”这样的字符串将无法通过测试。

第二,

while(str !=null)

永远不会失败,因为str永远不会null。您需要测试是否为空:

while (str.length() > 0)
于 2012-05-19T05:00:01.123 回答