我想讓這個程序詢問用戶一個字符串和字符,然後告訴用戶字符串的數量人物。找不到這個java異常:「main」java.lang.StringIndexOutOfBoundsException:String index超出範圍:1
這是代碼:
import java.util.Scanner; // Needed for the Scanner Class
/*
This program ask you to enter a string and a character and then tells you how many times the character appears in the string.
*/
public class PC5
{ public static void main(String[] args) throw StringIndexOutOfBoundsException
{
int times = 0; // To keep track of the times the charcater appears in the String
String str1; // To get the string you want to check
String str2; // To get the string for the character you want to check in the String.
char myChar; // To get the character from str2
Scanner keyboard = new Scanner(System.in);
// Get the string you want to check
System.out.print("Enter the string you want to check: ");
str1 = keyboard.nextLine();
// To get the charcater
System.out.print("Enter the character you want to check: ");
str2 = keyboard.nextLine();
myChar = str2.charAt(0);
for (int i = 0; i < str1.length(); i++)
{
if (str2.charAt(i) == myChar)
times += 1;
}
System.out.println("The number of times the character appears in the string is: " + times);
}
}
我得到這個例外,當我運行這個程序:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:695)
at PC5.main(PC5.java:36)
謝謝你的幫助。
這意味着(廢話!)的字符串索引超出範圍。做一些調試 - 你知道哪一行有錯誤,所以調試應該是微不足道的。 –