![](/img/trans.png)
[英]How to prevent my app from crashing when there is no input or if input is invalid
[英]How to prevent my program from crashing due to a user's input
我正在嘗試實現“識別語言字符串”的算法
L = {'w $ w':w是$以外的可能的空字符串,w'= reverse(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;
}
}
線程“主”中的異常java.lang.StringIndexOutOfBoundsException:字符串索引超出范圍:java.lang.String.charAt(未知源)為4,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");
}
聽起來這可能就足夠了:
if (inputString == null || !inputString.contains("$")) {
return false; // empty string not in L
}
可能的問題是空指針異常,請嘗試在函數頂部添加此行
public boolean isInLanguage(String inputString)
{
if(inputString == null){
return false;
}
...
...
如果仍然崩潰,請完成代碼,然后需要提供運行代碼時遇到的錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.