I have been trying to write a Java program which converts the first letter of every word of a string into a capital letter. Right now it looks like this:
package strings;
import java.util.Scanner;
public class small_cap {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence");
String st = sc.next();
String str = " " + st;
int j = 0; char chr = ' ';
for (int i = 0; i < str.length(); i++){
j = i + 1;
chr = str.charAt(j);
if (chr == ' '){
char a = Character.toUpperCase(str.charAt(j));
str = str.replace(str.charAt(j), a);
}
else{
char a = Character.toLowerCase(str.charAt(j));
str = str.replace(str.charAt(j), a);
}
}
System.out.println(str);
}
}
Unfortunately I keep on getting the error:
java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:658)
at small_cap.main(small_cap.java:19)
I don't really see any fault in the code. Can someone please point out where I am going wrong?
for (int i = 0; i < str.length(); i++){
j = i + 1;
When i
reaches the last valid index length - 1
, j
will be equal to length
, which is out of bounds.
I don't really see the point of the j
variable to begin with - did you mean to use i
somewhere else inside the loop as well, or should you just make your loop start from 1? Or did you perhaps mean to check the previous character by doing j = i - 1;
(in that case make sure you don't read before index 0)
You are using String.Replace which will replace all matching characters irrespective of their position.
import java.util.Scanner;
public class small_cap { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the sentence"); String st = sc.nextLine(); String str = " " + st; int j = 0; char chr = ' '; for (int i = 0; i < str.length()-1; i++){ j = i+1; chr = str.charAt(i); if (chr == ' '){ char a = Character.toUpperCase(str.charAt(j)); str = str.substring(0,j)+a+str.substring(j+1); } else{ char a = Character.toLowerCase(str.charAt(j)); str = str.substring(0,j)+a+str.substring(j+1); } } System.out.println(str); }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.