Home » Utilities & Tools » Java Console Input Example

Java Console Input Example

Popular Links

  • None


This is a simple example of taking console input and invoking a method based on the user inputs. There are many ways to do this and couple of them are listed below.

1) Using  simple    java.io.BufferedReader;
2) Using     java.io.Console;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


/**
* Sample Console Input example
* @author manjul
*
*/
public class ConsoleInput {

public static void main(String[] args) throws IOException, InterruptedException {
  while(true){
  int in = takeInput();

  switch (in) {
   case 1:
   fun1();
   break;

   case 2:
   fun2();
   break;

   default:
   exit();
   break;
  }
}
}

private static int takeInput() throws IOException{
   StringBuilder sb = new StringBuilder();
   sb.append("Please Select an option: \n");
   sb.append("1: Show Songs\n");
   sb.append("2: Add Songs\n");
   sb.append("3: Exit \n");
   System.out.println(sb.toString());
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   String input = br.readLine();
   System.out.println("You Selected: " + input);

   int in = -1;
   try{
    in = Integer.parseInt(input);
   }catch(Exception ex){
   System.out.println("Enter correct value [1,2,3]");
 }
   return in;
}

private static void fun1(){
   System.out.println("Heloo 1");
}

private static void fun2(){
   System.out.println("Hello 2");
}

private static void exit(){
   System.out.println("Thanks..");
   System.exit(1);
}

}


1 Comment

  1. I am a tourism worker, for I am here to enjoy the content, I hope I can communicate with you, my msn : jkboy@263.net</a Click http://pepij.nl/justgoo100645

Leave a comment