Note that there are some explanatory texts on larger screens.

plurals
  1. PONoSuchElement exception when using Scanner
    primarykey
    data
    text
    <p>I'm trying to get input from the console a second time within the program using <code>Scanner</code>s but when calling a second <code>Scanner</code> in another method it’s coming up with NoSuchElement exception. </p> <p>If I remove <code>startMenu()</code> from running <code>fileReader()</code> it works, however for some reason after running it throws the exception. </p> <pre><code> public class Garden { public static final Garden GARDEN = new Garden(); //variable declartaions removed public static void main(String[] args) { if (null != args &amp;&amp; 0 &lt; 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 } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload