gpt4 book ai didi

java - 请求 int 输入时出现奇怪的返回值

转载 作者:行者123 更新时间:2023-12-01 06:39:02 26 4
gpt4 key购买 nike

我有以下代码:

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

我忽略了哪些明显的事情?

最佳答案

方法stdin.read();不是获取int值的正确方法。使用stdin.readLine(),

  positiveInt = Integer.parseInt(stdin.readLine());

关于java - 请求 int 输入时出现奇怪的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20257346/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com