Finding all uppercase letters of a string in java
Asked Answered
R

10

11

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.

Rectitude answered 31/10, 2012 at 3:9 Comment(3)
Just mentioning, give meaningful names to your variable/class/method names rather than naming them x,y,z and wNavada
Definitely. Notice that in my answer I used identifiers such as inputString. use i, j, k for indexes with embedded loops, and you can use c for a character, but anything else give it a proper name.Wavelength
Should be for(int y = 0; y < z; y++) ..Disproportionate
N
19
for(int y = 0; y <= z; y++){

should be

for(int y = 0; y < z; y++){

Remember array index starts from ZERO.

String length returns

the number of 16-bit Unicode characters in the string

Because loop started from ZERO, loop should terminate at length-1.

Nealey answered 31/10, 2012 at 3:10 Comment(1)
Thanks man, I feel really foolish now haha. Beginners mistake.Rectitude
W
10

The array index out of bounds is due to the for loop not terminating on length - 1, it is terminating on length Most iterating for loops should be in the form:

for (int i = 0; i < array.length; i++) {
    // access array[i];
}

It's the same with a string.

Perhaps a cleaner way would be:

String inputString; // get user input

String outputString = "";

for (int i = 0; i < inputString.length; i++) {
    c = inputString.charAt(i);
    outputString += Character.isUpperCase(c) ? c + " " : ""; 
}
System.out.println(outputString);

Edit: Forgot String Doesn't implement Iterable<Character>, silly Java.

Wavelength answered 31/10, 2012 at 3:18 Comment(0)
S
8

With Java 8 you can also use lambdas. Convert the String into a IntStream, use a filter to get the uppercase characters only and create a new String by appending the filtered characters to a StringBuilder:

Scanner in = new Scanner(System.in);
System.out.print("Please give a string: ");
//Uppercase
String isUp = in.next()
        .chars()
        .filter(Character::isUpperCase)
        .collect(StringBuilder::new, // supplier
                StringBuilder::appendCodePoint, // accumulator
                StringBuilder::append) // combiner
        .toString();
System.out.println("The uppercase characters are " + isUp);
//Uppercase

Inspired by:

Sublimation answered 4/1, 2017 at 12:28 Comment(0)
C
4

Try this...

Method:

public int findUpperChar(String valitateStr) {
    for (int i = valitateStr.length() - 1; i >= 0; i--) {
        if (Character.isUpperCase(valitateStr.charAt(i))) {
            return i;
        }
    }
    return -1;
}

Usage:

String passwordStr = password.getText().toString();

 .......

int len = findUpperChar(passwordStr);

if ( len != -1) {

      capitals exist.   

  } else {

      no capitals exist.            
}
Cawthon answered 8/10, 2014 at 18:21 Comment(0)
N
2

The simplest way I know is to use regex replacement.

isUp = x.replaceAll("[^A-Z]", "");

In simple terms, this uses a regular expression which matches any character which is not in the A-Z range, and replaces it with an empty string.

Nilsanilsen answered 11/2, 2020 at 22:10 Comment(0)
S
1

Hi one of the easy step to find uppercase char in a given string...

Program

import java.io.*;
public class testUpper 
{
    public static void main(String args[]) throws IOException
    {
        String data,answer="";
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter any String : ");
        data=br.readLine();
        char[] findupper=data.toCharArray();
        for(int i=0;i<findupper.length;i++)
        {
            if(findupper[i]>=65&&findupper[i]<=91) //ascii value in between 65 and 91 is A to Z
            {
                answer+=findupper[i]; //adding only uppercase
            }
        }
        System.out.println("Answer : "+answer);
    }
}

Output

Enter any String :

Welcome to THe String WoRlD

Answer : WTHSWRD

Salvation answered 31/10, 2012 at 4:26 Comment(0)
H
0

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.

import java.util.Scanner;

public class P43 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Please give a string: ");
        String x = in.next();
        x.chars().filter(c -> Character.isUpperCase(c))
                .forEach(c -> System.out.print((char) c + " "));
    }
}

Sample input:

saveChangesInTheEditor

Sample output:

C I T E

Haywoodhayyim answered 14/9, 2018 at 3:30 Comment(0)
M
0
import java.util.Scanner;
class Demo
{
    public static void main(String[] args)
    {
         StringBuilder s=new StringBuilder();
         Scanner input = new Scanner(System.in);
         System.out.println("Enter your String");
         String str= input.nextLine();

         for(int i=0; i<str.length(); i++)
         {
            if(Character.isUpperCase(str.charAt(i)))
            {
               System.out.print(str.charAt(i)+" ");
            }
         }
      }
}
Maureenmaureene answered 17/9, 2019 at 16:51 Comment(0)
C
-1
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter the number");
    String str= input.nextLine();

    int ascii;
    for(int i=0; i<str.length(); i++) {
        ascii = str.charAt(i);
        System.out.println(ascii);
        if (ascii >= 65 && ascii <= 90) {
            System.out.println("captal letter found ::: "+ascii);
        }
    }
}
Cl answered 8/2, 2017 at 18:19 Comment(1)
Hmm, there are 50442 letter characters, 1155 of which are uppercase. ASCII is not relevant. charAt returns a UTF-16 code unit. UTF-16 is an encoding for the Unicode character set.Repetitive
F
-1
public class Cama {

public static void main(String[] args) {
    String camal = "getStudentByName";
    String temp = "";
    for (int i = 0; i < camal.length(); i++) {
        if (Character.isUpperCase(camal.charAt(i))) {
            System.out.print(" " + Character.toLowerCase(camal.charAt(i)));
        } else if (i == 0) {
            System.out.print(Character.toUpperCase(camal.charAt(i)));
        }else{
            System.out.print(camal.charAt(i));
        }
    }
}
}
Forereach answered 4/10, 2018 at 17:32 Comment(2)
Output = Get student by nameForereach
This answer has no explanations as to why it is useful. This code would be much more useful if there was also an explanation of how this code answers the users question.Piceous

© 2022 - 2024 — McMap. All rights reserved.