Mattkx4
Mattkx4

Reputation: 309

Proper way to get User Input from Console

I have a little question for you brilliant people!

I'm in the process of making a little console game, nothing too fancy, but certainly not simple, and would like to figure out a more efficient way to do something! That something I would like to do is get input from the user!

From the beginning I was taught to use Scanners to get user input from a console! So that's what I have always used! Below is an example of what I would write.

package com.mattkx4.cgamedev.main;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // Print out a message asking the user if ready
        System.out.println("Are you ready to continue? (Enter \"YES\" or \"NO\")");

        // Initialize a Scanner
        Scanner s = new Scanner(System.in);

        // Initialize a String to hold the User Input
        String in = s.nextLine();

        // Check the input with IF statements
        if(in.equalsIgnoreCase("YES")) {
            System.out.println("Let's continue!");
        }else if(in.equalsIgnoreCase("NO")) {
            System.out.println("Goodbye!");
            s.close();
            System.exit(0);
        }else{
            System.out.println("Please input a correct response!");
            main(null);
        }
    }
}

I'm absolutely sure there is a more efficient or easier way to do this! Any suggestions would be appreciated!

Thanks in advance -Matthew

Upvotes: 1

Views: 1890

Answers (1)

Braj
Braj

Reputation: 46871

The proper way is always illustrated in Oracle Java Tutorial itself.

Read it here I/O from the Command Line and find the sample code as well.


EDIT

Some points:

  • calling main() method again will initialize all the things again.
  • try with switch-case in case of multiple checks.
  • you can achieve the same functionality using do-while loop.

Sample code:

public static void main(String args[]) throws IOException {

    Console c = System.console();
    if (c == null) {
        System.err.println("No console.");
        System.exit(1);
    }

    boolean isValidResponse = false;
    do {
        String response = c.readLine("Are you ready to continue? (Enter \"YES\" or \"NO\"): ");
        switch (response.toUpperCase()) {
            case "YES":
                isValidResponse = true;
                System.out.println("Let's continue!");
                break;
            case "NO":
                isValidResponse = true;
                System.out.println("Goodbye!");
                break;
            default:
                isValidResponse = false;
                System.out.println("Please input a correct response!");
                break;
        }
    } while (!isValidResponse);
}

Upvotes: 2

Related Questions