如何防止我的程序因用户输入而崩溃

时间:2013-10-14 00:23:26

标签: java stack

我正在尝试实现一种算法“用语言识别字符串”

  

L = {'w $ w':w是除$以外的可能空字符串,   w'=反向(w)}

我的问题是每当我输入任何东西而没有$时,它会在while循环中崩溃。什么是防止它崩溃的最佳方法?

public boolean isInLanguage(String inputString)
{
        StackReferenceBased stack1 = new StackReferenceBased(); 
        StackReferenceBased stack2 = new StackReferenceBased(); 
        Object qItem;
        Object sItem;
        int index = 0; 

        if (inputString.length() == 0)
        {
            return false; // empty string not in L  
        }

        else if (inputString.length() == 1)
        {
            return true; 
        }

        **while (inputString.charAt(index) != '$')**
        { 
            // save the first half of the string
            stack1.push(inputString.charAt(index));

            ++index;
        }  

        // index points to '$' or its value > than inputString.length()
        while (index < inputString.length()-1)
        {
            // save the second half of the string
            ++index;
            stack2.push(inputString.charAt(index));
        } 

        do
        {
            // match the first half of the string with the second half
        if ((stack1.isEmpty() && !stack2.isEmpty()) ||(!stack1.isEmpty() && stack2.isEmpty()))
        {
            return false;
        }
        qItem = stack1.peek();
        sItem = stack2.peek();

        if (qItem != sItem)
        {
            return false;
        }

        if (!stack1.isEmpty())
        {
            stack1.pop();
        }

        if (!stack2.isEmpty())
        {
            stack2.pop();
        }

        }while (!stack1.isEmpty() || !stack2.isEmpty());


        if (stack1.isEmpty() && stack2.isEmpty())
        {
            return true;
        }
        else
        {
            return false; 
        }


}
  

线程“main”中的异常java.lang.StringIndexOutOfBoundsException:   字符串索引超出范围:java.lang.String.charAt为4(未知   来源)at   assignmnet5.StackReferenceBased.isInLanguage(StackReferenceBased.java:87)     在assignmnet5.Question3.main(Question3.java:19)

这是我的主要内容:

public static void main(String[]args)
    {
        StackReferenceBased stack = new StackReferenceBased(); 

        String str;
         boolean bool;

         Scanner kb = new Scanner(System.in);
         System.out.println( "Enter a string to be checked by the algorithm : ");
         str = kb.next();

        **bool = stack.isInLanguage(str);**
        if (bool == true)
           System.out.println( "The string is in language");
        else 
            System.out.println("The string is not in language");
    }

2 个答案:

答案 0 :(得分:1)

听起来这可能就足够了:

    if (inputString == null || !inputString.contains("$")) {
        return false; // empty string not in L  
    }

答案 1 :(得分:0)

可能的问题是空指针异常,尝试在函数顶部添加此行

public boolean isInLanguage(String inputString)
{
    if(inputString == null){
        return false;
    }
...
...

完成您的代码 如果您仍然遇到崩溃,则需要提供运行代码时出现的错误。