简体   繁体   English

Java中java charAt方法的问题

[英]Problems with java charAt method in Java

The problem is this: Write the code that will translate hexadecimal digits (A - F, accept lower and uppercase) to its decimal values.问题是这样的:编写将十六进制数字(A - F,接受小写和大写)转换为其十进制值的代码。

The input contains an character.输入包含一个字符。 If it is the hexadecimal digit print its decimal value else print -1.如果是十六进制数字打印其十进制值,否则打印-1。

I have a solution but I don't properly understand this line ch = input.nextLine().charAt( 0 );我有一个解决方案,但我没有正确理解这一行ch = input.nextLine().charAt( 0 );

import java.util.Scanner;

public class JavaApp {

    public static void main(String[] args) {

      Scanner input = new Scanner(System.in);
      char ch;
      int digit;
  
      ch = input.nextLine().charAt( 0 );
      if( ch >= '0' && ch <= '9') digit = ch - '0';
      else 
          if( ch >= 'a' && ch <= 'f') digit = ch - 'a' +10;
          else  
              if( ch >= 'A' && ch <= 'F') digit = ch - 'A' +10;
              else digit = -1;
      
      System.out.println( digit );
    }
}

Thanks for help感谢帮助

因为您从 Scanner 获得的输入是一个 String 它被charAt转换为一个 char 。

Scanner does not support nextChar() to read a single character. Scanner 不支持 nextChar() 读取单个字符。 https://www.geeksforgeeks.org/gfact-51-java-scanner-nextchar/ https://www.geeksforgeeks.org/gfact-51-java-scanner-nextchar/

Hence, even though the input given in STDIN is a single character, Scanner.nextLine() considers it as String.因此,即使 STDIN 中给出的输入是单个字符, Scanner.nextLine()将其视为字符串。 So, in order to get first character of that String, charAt(0) is being used.因此,为了获取该字符串的第一个字符,将使用charAt(0)

More info on scanner nextLine() method - https://www.baeldung.com/java-scanner-nextline有关扫描仪 nextLine() 方法的更多信息 - https://www.baeldung.com/java-scanner-nextline

Updated:更新:

To make sure the character is digit, Character.isDigit can be used.要确保字符是数字,可以使用Character.isDigit What is the best way to tell if a character is a letter or number in Java without using regexes? 在不使用正则表达式的情况下,在 Java 中判断字符是字母还是数字的最佳方法是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM