有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java输入返回不正确的值

我使用此official example接收用户的输入,然后打印它:

import java.io.IOException;

    public class MainClass {
    
      public static void main(String[] args) {
        int inChar;
        System.out.println("Enter a Character:");
        try {
          inChar = System.in.read();
          System.out.print("You entered ");
          System.out.println(inChar);
        }
        catch (IOException e){
          System.out.println("Error reading from user");
        }
      }
    }

问题是,它总是返回不正确的值。例如,当输入10时,它返回49,而我希望返回10! 这个问题的原因是什么?我如何解决它


共 (3) 个答案

  1. # 1 楼答案

    如果要打印字符并将其强制转换为char,则返回字符的int值:

    System.out.println((char) inChar);
    

    这将只打印由于系统原因而输入的第一个字符的值。在里面read()只读取第一个字节

    要阅读整行文字,可以使用Scanner

    import java.util.Scanner;
    
    public class MainClass {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            System.out.println("Write something:");
            // read input
            String line = scanner.nextLine();
            System.out.print("You entered ");
            System.out.println(line);
          }
    }
    
  2. # 2 楼答案

    试试这个片段

    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedReader brInput = new BufferedReader(isr);
    String strInput = brInput.readLine();
    System.out.println("You wrote "+strInput);
    
  3. # 3 楼答案

    System.in.read reads only first byte from input stream

    所以如果你进去

    123

    第一个字符是1。所以它对应的ASCII码是49

    如果我们进去

    254

    第一个字符是2。所以它对应的ASCII是50

    编辑:这也解释了here