Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 14
이번 예외는 인덱스 값으로 마이너스 값을 대입하거나, 문자열 길이보다 큰 인덱스 값을 대입하면 발생한다.
입력값에 영어 문자열을 입력한 후에 문자열 안의 모음과 자음의 개수를 나타내는 프로그램이다.
for문 안에 text.length() 값, 즉 입력값 문자열의 길이까지 charAt( )메소드 반복을 시키면 예외가 발생한다.
이때 가장 마지막 문자열까지 확인하고 싶어 length( )메소드를 사용하였지만
주의 할 점은 Java의 모든 인덱스가 1이 아닌 0부터 시작한다는 것이다.
때문에 length( ) 메소드를 통해 길이를 알고 난 후 -1 처리를 해주어야 예외가 발생하지 않는다.
예외 뒤의 String index out of range: number 은 length( )를 통한 문자열 길이보다 큰 인덱스 값(자리)을 의미.
아래와 같이 for문 안에 text.length( )-1 를 입력 후 반복했을 때 예외가 발생하지 않음을 확인했다.
import java.util.Scanner;
public class A2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
String text = sc.nextLine();
int numOfConsonant = 0;
int numOfVowels = 0;
for (int i = 0; i <= text.length()-1; i++) {
char vowels = text.charAt(i);
char consonants = text.charAt(i);
if (vowels == 'a' || vowels == 'A' ||
vowels == 'e' || vowels == 'E' ||
vowels == 'i' || vowels == 'I' ||
vowels == 'o' || vowels == 'O' ||
vowels == 'u' || vowels == 'U' ) {
numOfVowels++;
} else if (consonants == ' ') {
} else {
numOfConsonant++;
}
}
System.out.println("Num. of Consonant : " + numOfConsonant);
System.out.println("Num. of Vowels : " + numOfVowels);
}
}
}
Reference
String (Java Platform SE 7 )
Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argum
docs.oracle.com
'JAVA' 카테고리의 다른 글
[Java] 📚 BufferedReader / BufferedWriter를 활용한 빠른 입출력 (3) | 2022.05.28 |
---|---|
[Java] 📚 String / StringBuffer / StringBuilder (1) | 2022.05.22 |
[JAVA] Exception in thread "main" java.lang.ArithmeticException: / by zero (2) | 2022.03.09 |
JAVA - 반복문 (for문) (0) | 2022.02.05 |
JAVA - 배열 (Array) (2) | 2022.01.31 |