在Java中查找字符串的所有大写字母 [英] Finding all uppercase letters of a string in java

查看:116
本文介绍了在Java中查找字符串的所有大写字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图在用户输入的字符串中查找所有大写字母,但我不断遇到此运行时错误:

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)

我觉得很愚蠢,但我只是想不通,oracle甚至在有关

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.

推荐答案

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

应该是

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

记住数组索引从零开始.

Remember array index starts from ZERO.

字符串长度返回

字符串中16位Unicode字符的数量

the number of 16-bit Unicode characters in the string

由于循环从零开始,因此循环应以长度1终止.

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

这篇关于在Java中查找字符串的所有大写字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆