【问题标题】:By using while/for loop, how to subtract ONLY the uppercase of a line input by users?通过使用 while/for 循环,如何仅减去用户输入的行的大写?
【发布时间】:2016-07-13 21:23:57
【问题描述】:

这是我的代码,我使用is.upperCase 进行检查,但它似乎不起作用。而且我无法将所有大写字母连接在一起。任何建议和帮助将不胜感激!

import java.util.Scanner;

public class UpperCase  {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in); 
        System.out.print("Please input a random line that contain uppercase letters in any positions: ");
        String str = in.next();

        int i = 0;

        while (i < str.length() - 1) {
            if(Character.isUpperCase(i)) { 
                char upperLetter = str.charAt(i);
            }    

            Object outputLetter = str.charAt(0) + str.charAt(i++);
            char upperLetter = str.charAt(i++);
        }

        System.out.println("The uppercase letters are:" );
    }
}

【问题讨论】:

    标签: java loops while-loop char uppercase


    【解决方案1】:

    我想下面会解决你的问题。

            Scanner in = new Scanner(System.in);
            System.out.print("Please input a random line that contain uppercase letters in any positions: ");
            String str = in.nextLine();
            char[] cr = str.toCharArray();
            StringBuffer stringBuffer = new StringBuffer();
            for(int i=0;i<cr.length;i++){
                if(Character.isUpperCase(cr[i])){
                    stringBuffer.append(cr[i]);
                }
            }
            System.out.println("The uppercase letters are:" + stringBuffer);
    

    【讨论】:

      【解决方案2】:

      首先,您的想法是正确的,但是您的实施方式存在一些错误 1. isUperCase of i -> 错误 2. outputLetter 应该在循环外声明以避免重新初始化数据 3. outputLetter 应该类似于 outputLetter += anUpperCase 4. 最后,参考下面的代码

      public static void main(String[] args) {
      
              Scanner in = new Scanner(System.in);
              System.out.print("Please input a random line that contain uppercase letters in any positions: ");
              String str = in.next();
              in.close();
              int i = 0;
              String result = "";
              while (i < str.length() - 1) {
      
                  char aChar = str.charAt(i);
      
                  if (Character.isUpperCase(aChar)) {
                      result += aChar;
                  }
                  i++;
              }
              System.out.println("The uppercase letters are: " + result);
          }
      

      【讨论】:

      • 非常感谢您的帮助!!我将尝试运行这两个代码。再次感谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多