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

    0
    17
    Spread the love
    • 1
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
      1
      Share



    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
    Don't miss out!
    Subscribe To Newsletter

    Receive top technical news, lesson ideas, travel tips and more!

    Invalid email address
    Give it a try. You can unsubscribe at any time.

    Spread the love
    • 1
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
      1
      Share

    LEAVE A REPLY

    Please enter your comment!
    Please enter your name here