0

Why is it that I have to delete/nullify input.close(); to allow the next scan to take part? Does the second closing function inputtwo.close(); close both?

Sorry for my bad vocab. I really new to this stuff.

import java.util.Scanner;
public class FieldTesting {
public static void main(String[] args) {

    Scanner input = new Scanner(System.in); 
    System.out.println("Enter the month number (1 - 12): ");
    int month = input.nextInt();

    String monthString;

    switch (month) {
    case 1:
        monthString = "January";
        break;
    case 2:
        monthString = "February";
        break;
                //etc...
    default:
        monthString = "Invalid month";
        break;
    }

    System.out.println(monthString);
    /* Why must I delete this close statement?
    input.close();
    */
    Scanner inputtwo = new Scanner(System.in);

    System.out.println("Start or Stop? ");
    String command = inputtwo.nextLine();

    switch (command) {
    case "start":
        System.out.println("Machine Started");
        break;
    case "stop":
        System.out.println("Machine Stopped");
        break;
    default:
        System.out.println("Not a command.");
        break;
    }
    input2.close();
}
}
Mang
  • 1
  • 1
    recommend you only ever create one scanner and only use that. there is no need to create the second and as you've noticed, having 2 only causes problems. – slipperyseal Nov 21 '17 at 23:37
  • Yes. But scanners can buffer input, so your second scanner could potentially start from _anywhere_ in the input stream. – xiaofeng.li Nov 21 '17 at 23:38
  • Which means you need to code very carefully just to avoid something that's really hard to detect. Bad idea. – xiaofeng.li Nov 21 '17 at 23:40

0 Answers0