【问题标题】:Trying to read through a character array in java试图通过java中的字符数组读取
【发布时间】:2012-08-31 23:05:51
【问题描述】:

我是一个想学习java的新手。我正在为我的班级做一个项目,我们正在创建一个十六进制-十进制转换器。我已经完成了转换,但是当我打印出十六进制结果时,字母(因为十六进制包含 A-F)以小写形式打印出来。我尝试使用以下代码读取字符数组并将所有小写字符大写:

int i = Integer.parseInt(input);
String hex = Integer.toHexString(i);
char[] hexchar = hex.toCharArray();
for(int j=0; j<=hexchar.length; j++){
   if(hexchar[j].equals("a")){
     hexchar[j]=hexchar[j].toUpperCase();
} 
}

我打算为字母 a-f 设置此代码,但我不断收到的错误是无法延迟 Char 数组。有谁知道是否有办法读取 char 数组或可以提交可能的解决方法?

【问题讨论】:

    标签: java string char


    【解决方案1】:

    您不能将toUpperCase 应用于原始字符:it is a method of the String class。下面的代码应该做你想做的:

    int i = Integer.parseInt(input);
    String hex = Integer.toHexString(i).toUpperCase();
    

    【讨论】:

      【解决方案2】:

      char 是一个原语。也许你的意思是Character.toUpperCase

      final int i = Integer.parseInt(input);
      String hex = Integer.toHexString(i);
      final char[] cs = hex.toCharArray();
      for (int j = cs.length; j > 0; --j) {
        final char ch = cs[j];
        if (Character.isLetter(ch)) {
          cs[j] = Character.toUpperCase(ch);
        }
      }
      hex = new String(cs);
      

      不过,我不明白这一点;你真的应该只使用String.toUpperCase,所以...

      final String hex = Integer.toHexString(i).toUpperCase();
      

      【讨论】:

        【解决方案3】:

        这不应该完美吗?

        int i = Integer.parseInt(input);
            String hex = Integer.toHexString(i);
            System.out.println(hex);
            System.out.println(hex.toUpperCase());
        

        它将所有字符从 a-f 更改为 A-F 并保持数字不变。

        【讨论】:

          【解决方案4】:

          给你:

          import java.util.Scanner;
          
          public class classy
          {
              public static void main(String args[])
              {
                  Scanner input = new Scanner( System.in );
          
                  int i;
          
                  System.out.println("Please enter an integer");
                  i=input.nextInt();
          
                  System.out.printf( "Your Integer  is  %d\n", i );
          
          
                  String hex=Integer.toHexString(i).toUpperCase();
                    System.out.println("Your Hexadecimal Number is  "+hex);
              }
          }
          

          【讨论】:

            猜你喜欢
            • 2012-12-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-01-03
            • 1970-01-01
            • 2016-11-04
            • 2019-03-26
            • 1970-01-01
            相关资源
            最近更新 更多