Header Ads

How to take user Input in java::: How I coded it





Most of the time when we start using little advanced coding we use to take values from user.
in C it is simple.we can write

getchar(); and gets(); are like scanf()

1) getchar(); takes one symbol. IF i want 2 symbol, I should write getchar(); getchar();
2) gets(); takes full string with spaces. For example: If I write "Ask QTP". Scanf takes "Ask QTP"
3) scanf(); takes symbols before space. For example: If I write "Ask QTP". Scanf takes only "ASK"

But in java what could be a solution??
In java there are two ways to take input.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 // read the username from the command-line; need to use try/catch with the // readLine() method
 try {
 userName = br.readLine();
 }
 catch (IOException ioe) {
 System.out.println("IO error trying to read your name!");
 System.exit(1);
 }*/


You can ask for the user input
// prompt the user to enter their name
 String userName = null;
 userName = JOptionPane.showInputDialog(null, "What is your name?", "Enter your name", JOptionPane.QUESTION_MESSAGE);

The code will look like
import java.io.*;
public class ReadLine {
     public static void main (String[] args)
      {
       // prompt the user to enter their name
        System.out.print("Enter your name: ");
 // open up standard input
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 // read the username from the command-line; need to use try/catch with the // readLine() method
    try
      {
        userName = br.readLine();
      }
    catch (IOException ioe)
     {
      System.out.println("IO error trying to read your name!");
      System.exit(1);
      }
   System.out.println("Thanks for the name, " + userName);
    }
 } // end of ReadLine class
Code for dialogbox:
import javax.swing.JOptionPane;
public class ReadLine
   {
     public static void main (String[] args)
     {
      // prompt the user to enter their name String
       userName = null;
       userName = JOptionPane.showInputDialog(null, "What is your name?", "Enter your name", JOptionPane.QUESTION_MESSAGE);
     System.out.println("Thanks for the name, " + userName);
     }
 } // end of ReadLine class
Powered by Blogger.