我是Java的新手,所以我想创建一个简单的程序,它会让我输入一些随机值,然后打印它。问题是当我输入数字1,输出是51,输入3输出51,输入77输出55.这有什么问题?代码如下所示:
public static void main(String[] args) throws IOException
{
System.out.print("Input:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int val=br.read();
System.out.print("Output:");
System.out.println(val);
}
答案 0 :(得分:3)
您只需读取一个字符并打印unicode:)
尝试类似
的内容String s=br.readLine();
System.out.print("Output:");
System.out.println("Input " + s);
int val = Integer.parseInt(s):
System.out.println("As integer: " + val);
如果您只想阅读一个字符:
System.out.print("Input:");
Reader r = new new InputStreamReader(System.in);
int val = r.read();
System.out.print("Output:");
System.out.println((char) val);
如果您想阅读一位数字:
System.out.print("Input:");
Reader r = new new InputStreamReader(System.in);
int val = r.read() - '0';
System.out.print("Output:");
if (val < 0 || val > 9) {
System.out.println("error, digit expected");
} else {
System.out.println(val);
}
答案 1 :(得分:1)
你也可以使用BufferedReader作为
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input = reader.readLine();
input number = Integer.parseInt(input);
System.out.println(input);
}