Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.util.Scanner;

public class Main {
    private static int getChoice() {

        Scanner input = new Scanner(System.in);
        int choice = 1; //default value to force skip of first if statement check
        do {
            if (choice < 1 | choice > 4)
                System.out.println("Invalid choice...");
            System.out.print("Choice: ");
            /*This while loop checks the buffer stream for the next incoming input.
             *the purpose is to check if the input can be assigned an int value.
             *at this time choice has not be assigned*/
            while (!input.hasNextInt()) { // ask for an input, if input NOT nextInt then:
                input.next(); // consumes the token and returns to top of loop for another token
                System.out.print("Try again: "); //don't want println as that would shift cursor to new line
            }
            choice = input.nextInt(); //once the input has been found to be an int, assign to choice
            /*now choice needs to be checked for the correct range of values.
             * if its not within 1-4 then repeat while loop above*/
        } while (choice < 1 | choice > 4);
        //input.close();
        return choice;
    }
}