在功能中找不到符号。

时间:2017-11-07 21:03:33

标签: java user-input

我试图在函数中获取一些用户输入但由于某种原因我的代码将无法识别我的输入流。当我去编译时,我在第81行得到一个错误,说找不到reader.readLine()。有谁知道如何解决这一问题?或者是否可以在初始执行循环中发生运行功能而没有任何问题?

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;
}

}

3 个答案:

答案 0 :(得分:1)

readermain()方法的范围内定义。它不存在于run()

的范围内

您可以将其定义为类的成员,因此两种方法都可以访问它。或者将其作为方法之间的参数传递。

答案 1 :(得分:0)

阅读器是在main方法中定义的,其范围在其中,要在run方法中访问它,您可以在 run()方法中传递它,以便它可以在那里找到。

答案 2 :(得分:-1)

BufferedInput阅读器定义应该在main函数之外声明,即在类内部声明它然后它将是全局的并且可以通过类的任何方法访问。

Class name {
       buffereInput reader = ....
 .....
 }