How to get an input string in java.

You would have used SOP’s (System.out.print) statement ‘n’ number of times. But you may have missed on getting input string in java. Here are few ways of doing this.


1. Scanner class: Java has “java.util.Scanner” provides us a way of reading a line from a input stream. If we set the input stream as “System.in”, we can use the next() method to read the input from the console.


Java Program to get an input string.


import java.util.Scanner;
class Crap{
   public static void main(String [] args){
       Scanner s = new Scanner(System.in);
       System.out.println("Enter a text:");
       System.out.print(s.next());
   }
}

2. JOptionPane class: JOptionPane class provides us with a UI input window for getting inputs from UI instead of console.


Java Program to get an input string.


import javax.swing.JOptionPane;
class Crap{
   public static void main(String [] args){
       String input = JOptionPane.showInputDialog("Enter input text: ");        
       System.out.print(input);
   }
}

You can use above method to get int (or numeric) values. All you have to use is parse methods provided by Wrapper classes of the associated type.

For getting an int from String use:

int input = Integer.parseInt(inputString)

For getting float from String use:

float input = Float.parseFloat(inputString)

Leave a Reply

Your email address will not be published. Required fields are marked *