2013-12-11 138 views
0

我试图从程序中第二次使用Scanner s从控制台获取输入,但在另一种方法中调用第二个Scanner时,它会产生NoSuchElement异常。使用扫描仪时NoSuchElement异常

如果我从运行fileReader()中删除startMenu()它可以工作,但是由于某种原因运行后会抛出异常。

public class Garden { 
    public static final Garden GARDEN = new Garden(); 
    //variable declartaions removed 
    public static void main(String[] args) { 
     if (null != args && 0 < args.length) { 
      GARDEN.fileName = args[0].trim(); 
     } 
     if (GARDEN.fileName != null) { 
      GARDEN.fileReader(GARDEN.fileName); 
     } else { 
      GARDEN.fileReader(); 
     } 

     GARDEN.startMenu(); 
     int mainI = 0; 
     while (mainI != 1000000) { 
      try { 
       Thread.sleep(0); 
      } catch (InterruptedException e) { 
      } 
      GARDEN.daysWeather(); 
      GARDEN.anotherDay(); 
      mainI++; 
     } 
    } 


    protected void fileReader() { // asks for file name for config file 
     System.out.println("Enter File Name Please"); 
     Scanner cmdReader = null; 
     String cmdInput = null; 
     try { 
      cmdReader = new Scanner(System.in); 
      cmdInput = cmdReader.nextLine(); 
     } catch (NoSuchElementException noSuchElement) { 
      noSuchElement.printStackTrace(); 
      fileReader(); //throwing error here 
     } 

     //code removed 
    } 



    protected void startMenu() {// modified code from ATM lab (week2) 
    int selected = 0; 
     //code removed 
     Scanner climateScanner = new Scanner(System.in); 
     System.out.println("Select a number 1-4"); 
     selected = climateScanner.nextInt(); 
     switch (selected) { 
     case 1: // semiarid 
      weatherType = 10; //10% chance to rain 
      climateScanner.close(); 
      break; 
     case 2: // arid 
      weatherType = 20; //5% chance to rain 
      climateScanner.close(); 
      break; 
     case 3: 
      weatherType = 50; //2% chance to rain 
      tropicalWeather = true; 
      climateScanner.close(); 
      break; 
     case 4: 
      weatherType = 20;//5% chance to rain 
      storming = true; 
      climateScanner.close(); 
      break; 
     default: 
      System.out.println("Invalid Input try again"); 
      startMenu(); //using Recursion to ask for input again 
      break; 
     } 
     //code removed 
    } 
} 
+0

什么是'GARDEN'? –

+0

GARDEN是创建的单例不认为这是问题,因为它与GARDEN.fileReader()一起使用时,GARDEN.startMenu()不叫做 – user1642671

回答

1
GARDEN.startMenu();// method id not a static one. 

您无法访问,在这种方式。你必须初始化类或使你的方法是静态的。还有什么是GARDEN ??

好的,现在你已经编辑了你的代码。

再次

GARDEN.fileReader(GARDEN.fileName); // you are parsing input argument 
           // But method in your class is no argument method 
+0

或者使'startMenu' * static *。 – Maroun

+0

@MarounMaroun也增加了你的观点 –

+0

fileReader(GARDEN.fileName)只是fileReader()的另一个实例,它不是要求fileName在程序在控制台java中启动时采用它。Garden testA.txt将运行fileReader(fileName) java花园将运行fileReader() – user1642671

0

问题是2个不同的扫描仪(一个在开始菜单(),一个在READFILE())改变它,以便有在类变量扫描器扫描器=新扫描仪(System.in)和然后从方法内调用scanner.nextLine()