显示输出不符合预期
Displaying Output Not as Expected
对于以下程序,我希望输出为
Enter any Value : 3
You Entered 3
但我没有得到输出,而是在输出中 java 期待一些输入而不显示 "Enter any Value"。如果我输入任何值,那么它会将输出显示为
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();
}
}
consoleOutput.println
直到 close()
才打印任何内容。使用
System.out.println("Enter any Value : ")
而不是
consoleOutput.println("Enter any Value : ");
如果要查看文本,请关闭consoleOuput
。
consoleOutput.print("Enter any Value : ");
consoleOutput.close();
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()
方法来获取实际值。当然它会 return 字符串所以只需解析它以获得整数。
对于以下程序,我希望输出为
Enter any Value : 3
You Entered 3
但我没有得到输出,而是在输出中 java 期待一些输入而不显示 "Enter any Value"。如果我输入任何值,那么它会将输出显示为
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();
}
}
consoleOutput.println
直到 close()
才打印任何内容。使用
System.out.println("Enter any Value : ")
而不是
consoleOutput.println("Enter any Value : ");
如果要查看文本,请关闭consoleOuput
。
consoleOutput.print("Enter any Value : ");
consoleOutput.close();
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()
方法来获取实际值。当然它会 return 字符串所以只需解析它以获得整数。