Tuesday 27 January 2015

How to get input from user in java

We are using Scanner class to get input from user.Scanner class is present in java.util package so we import this package in our program. We first create an object of Scanner class and then we use the methods of Scanner class. Consider the statement
Scanner sc = new Scanner(System.in); 
1) nextLine to input a string
2) nextInt to input an integer
3) nextFloat to input a float

package basic;

import java.util.Scanner;

public class GetInputFromUser {

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter string");
String s1=sc.nextLine();
System.out.println("Enter number");
int i=sc.nextInt();
System.out.println("Enter double number");
double d=sc.nextDouble();
                System.out.println("s1="+s1)
System.out.println("i="+i);
System.out.println("d="+i);
;

}

}


//Output:

Enter string
i love my india
Enter number
123
Enter double number
233.22

s1=i love my india
i=123
d=123




No comments:

Post a Comment