我有以下代码:
import java.io.*;
public class ExamPrep2
{
public static int getPositiveInt()
{
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
int positiveInt = 0;
try
{
positiveInt = stdin.read();
if (positiveInt < 0) {
System.out.print("A negative int! -1");
return -1;
}
else {
System.out.print("Yay! " + positiveInt);
return positiveInt;
}
}
catch (IOException e) {
System.out.print("Positive int is NaN! -2");
return -2;
}
}
public static void main(String[] args)
{
System.out.print("Enter a positive integer:");
getPositiveInt();
}
}
但是当我输入数值时,我得不到我输入的相同值。
例如:
Enter a positive integer:1
Yay! 49
Enter a positive integer:-2
Yay! 45
Enter a positive integer:x
Yay! 120
我忽视了哪些明显的事情?
答案 0 :(得分:3)
这行代码正在从流中读取一个字符,因此它正在读取&#34; - &#34;并将其中断为一个整数,该整数将是> 0
positiveInt = stdin.read();
您需要阅读整行文字才能从流中获取 - 和1个字符。
你可以看一下ASCII表,看看1 = ASCII 49, - 是ASCII 45等等......
答案 1 :(得分:3)
您正在以字符形式阅读所有内容:
positiveInt = stdin.read();
这将返回一个char。当您输入1
时,它将返回此字符的ASCII值。这是49。
相反,您应该使用Scanner
。
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
请参阅以下示例:
public static void main(String[] args) {
char input = '1';
System.out.println((int) input);
}
输出:
49
答案 2 :(得分:3)
方法stdin.read();
不是获取int
值的正确方法。使用stdin.readLine()
,
positiveInt = Integer.parseInt(stdin.readLine());
答案 3 :(得分:2)
使用Scanner
课程阅读。 Scanner scanner = new Scanner(System.in);
然后scanner.nextInt()
。 BufferedReader
正在为您提供ASCII值。