So I'm trying to find all the uppercase letters in a string put in by the user but I keep getting this runtime error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 4
at java.lang.String.charAt(String.java:686)
at P43.main(P43.java:13)
I feel foolish but I just can't figure this out and oracle even talks about charAt on the page about java.lang.StringIndexOutOfBoundsException
Here is my code for finding the uppercase letters and printing them:
import java.io.*;
import java.util.*;
public class P43{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
//Uppercase
String isUp = "";
System.out.print("Please give a string: ");
String x = in.next();
int z = x.length();
for(int y = 0; y <= z; y++){
if(Character.isUpperCase(x.charAt(y))){
char w = x.charAt(y);
isUp = isUp + w + " ";
}
}
System.out.println("The uppercase characters are " + isUp);
//Uppercase
}
}
I'd really appreciate any input and or help.
The array index out of bounds is due to the for loop not terminating on
length - 1
, it is terminating onlength
Most iterating for loops should be in the form:It's the same with a string.
Perhaps a cleaner way would be:
Edit: Forgot
String
Doesn't implementIterable<Character>
, silly Java.Hi one of the easy step to find uppercase char in a given string...
Program
Output
Enter any String :
Welcome to THe String WoRlD
Answer : WTHSWRD
You can increase the readability of your code and benefit from some other features of modern Java here. Please use the Stream approach for solving this problem. Also, I suggest importing the least number of libraries into your class. Please avoid using .* while importing.
Sample input:
saveChangesInTheEditor
Sample output:
C I T E
should be
Remember array index starts from ZERO.
String length returns
Because loop started from ZERO, loop should terminate at length-1.
With Java 8 you can also use lambdas. Convert the
String
into aIntStream
, use a filter to get the uppercase characters only and create a newString
by appending the filtered characters to aStringBuilder
:Inspired by:
IntStream
as aString