我試圖圍繞這個問題繞過我的頭,任何幫助將不勝感激。我試圖讓用戶輸入一個字符串,從一個數字(1-9)開始。當輸入字符串時,我需要打印一個子字符串,但只能輸入輸入的數字。例如,如果用戶輸入「4大房子」,我的輸出應該是「4 bi」。我有它正確顯示,但是我的代碼很長時間以來很多其他語句如果語句。使用以數字開頭的字符串來顯示多個字符的子字符串
另一種方法是減少代碼行數量?
而且,是的,我得到一個「字符串索引超出範圍的」異常,如果如果字符串以4開頭,但只包含3個字符的用戶沒有輸入足夠的字符,即...
else if (text.substring(0,1).matches("[0-9]"))
{
if (text.substring(0,1).matches("1"))
{
String text2 = text.substring(0, 1);
System.out.println("The decoded string is: " + text2 + ", and starts with a 1!");
}
else if (text.substring(0,1).matches("2"))
{
String text2 = text.substring(0, 2);
System.out.println("The decoded string is: " + text2 + ", and starts with a 2!");
}
else if (text.substring(0,1).matches("3"))
{
String text2 = text.substring(0, 3);
System.out.println("The decoded string is: " + text2 + ", and starts with a 3!");
}
else if (text.substring(0,1).matches("4"))
{
String text2 = text.substring(0, 4);
System.out.println("The decoded string is: " + text2 + ", and starts with a 4!");
}
else if (text.substring(0,1).matches("5"))
{
String text2 = text.substring(0, 5);
System.out.println("The decoded string is: " + text2 + ", and starts with a 5!");
}
else if (text.substring(0,1).matches("6"))
{
String text2 = text.substring(0, 6);
System.out.println("The decoded string is: " + text2 + ", and starts with a 6!");
}
else if (text.substring(0,1).matches("7"))
{
String text2 = text.substring(0, 7);
System.out.println("The decoded string is: " + text2 + ", and starts with a 7!");
}
else if (text.substring(0,1).matches("8"))
{
String text2 = text.substring(0, 8);
System.out.println("The decoded string is: " + text2 + ", and starts with a 8!");
}
else if (text.substring(0,1).matches("9"))
{
String text2 = text.substring(0, 9);
System.out.println("The decoded string is: " + text2 + ", and starts with a 9!");
}
}
那麼如果第一個字符應該是1和9之間的數字,你不應該使用'[1-9]'而不是'[0-9]'?後者也會允許數字'0'。 – Tom 2014-11-22 23:41:34