我正在尝试在函数中获取一些用户输入,但由于某种原因,我的代码无法识别我的输入流。当我去编译时,我在第 81 行收到一个错误,说找不到 reader.readLine()。有谁知道如何解决这个问题?或者是否有可能让运行函数在初始 do-while 循环中发生而没有任何问题?
import java.io.*;
public class JavaLab3 {
public static void main(String[] args) {
// first we define our input streams.
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
// variable declarations
String sName, playAgain;
// we catch exceptions if some are thrown.
// an exception would be entering a string when a number is expected
try {
System.out.println("what is your name?");
// we read a string from the stream
sName = reader.readLine();
do {
run();
System.out.println(sName + "would you like to play again?");
System.out.println("Please answer in lowercase 'yes' or 'no'.");
playAgain = reader.readLine();
} while (playAgain != "no");
} catch (IOException e){
System.out.println("Error reading from user");
}
}
public static int maxRun (int runTotal) {
int highScore = 0;
if (runTotal > highScore) {
highScore = runTotal;
} else {
`highScore = highScore`}
return highScore;
}
public static int run () {
Integer currentRun = 0, uNumber, counter;
final Integer MAX = 4;
final Integer MAX_NUMBER = 100;
//While current total is less than the max
while (currentRun < MAX) {
System.out.println("Please enter a number.");
//store user number
uNumber = Integer.parseInt(reader.readLine()); //Line throwing the error.
//for each number under 5 repetitions
for (counter = 0; counter <= MAX_NUMBER ; counter++ ) {
if (uNumber < 0) {
System.out.println("Please enter a positive number.");
} else if ((uNumber % 2) != 0) {
System.out.println("Please enter an even number.");
} else {
//sets current total and restarts the loop
currentRun = uNumber + currentRun;
}
}
}
//Calls maxRun function to see if score the score is the highest.
maxRun(currentRun);
System.out.println("The max for this run was, " + currentRun + ".");
return currentRun;
}
}
reader
是在main()
方法的范围内定义的。它不存在于run()
范围内。
您可以将其定义为类的成员,以便两种方法都可以访问它。或者将其作为方法之间的参数传递。
读取器是在 main 方法内部定义的,其范围在 main 方法内部,要在 run 方法中访问它,您可以在 run() 方法中传递它,以便它可以在那里使用。
BufferedInput 读取器定义应该在 main 函数外部声明,即在类内部,然后它将是全局的,并且可以通过类的任何方法访问。
Class name {
buffereInput reader = ....
.....
}