有 Java 编程相关的问题?

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

java显示输出不符合预期

对于以下程序,我希望输出为

Enter any Value : 3
You Entered 3

但我并没有得到输出,相反,在输出中,java期待一些输入,而不显示“输入任何值”。如果我输入任何值,它将显示输出为

3
Enter any value : You Entered 3.

这是我的代码:

    import java.io.*;
    // System.in is an object of InputStream - byte stream

    class ConsoleInputDemo{
        public static void main(String args[]) throws IOException{
            BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in)); // This will convert byte stream to character stream
            PrintWriter consoleOutput = new PrintWriter(System.out); 

            consoleOutput.println("Enter any Value : ");
            int c= consoleInput.read();
            consoleOutput.write("You entered " + c);
            consoleInput.close();
            consoleOutput.close();

        }
    }

共 (2) 个答案

  1. # 1 楼答案

    System.out.print("Enter any Value :  ");
        try {
            int c=Integer.parseInt(new BufferedReader((new InputStreamReader(System.in))).readLine());
            System.out.println("Entered Character: " +c);
        } catch (IOException e) {
            e.printStackTrace();
        }
    

    这个简单的代码可能会帮助您实现您的需求read()只会给你ascii值,所以我使用readline()方法来获得实际值。当然,它会返回字符串,所以只需解析它就可以得到整数

  2. # 2 楼答案

    consoleOutput.println直到close()才打印任何内容。使用

     System.out.println("Enter any Value :  ")
    

    而不是

    consoleOutput.println("Enter any Value : ");
    

    如果想查看文本,请关闭consoleOuput

     consoleOutput.print("Enter any Value : ");
     consoleOutput.close();