Finding all uppercase letters of a string in java

前端 未结 10 1061
后悔当初
后悔当初 2021-01-12 14:28

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.lan         


        
相关标签:
10条回答
  • 2021-01-12 15:17
    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.

    0 讨论(0)
  • 2021-01-12 15:20

    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

    0 讨论(0)
  • 2021-01-12 15:22

    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:

    • Adam Bien - Streaming A String
    • Simplest way to print anIntStream as a String
    0 讨论(0)
  • 2021-01-12 15:23
    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);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题