There are four ways to take user input in Java
1. Command Line Arguments
2. Scanner Class of java.util package
3. InputStreamReader Class of java.io package
4. Console Class of java.io package
1. Command Line Arguments
class In_1
{
public static void main(String[] args)
{
String s1=args[0];
String s2=args[1];
System.out.println(s1+s2);
}
}
Stream in Java:
- System.out
- System.err
- System.in
class In_2
{
public static void main(String[] args)
{
System.out.println("Hello");
System.err.println("Hello");
try
{
int s=System.in.read();
System.out.println(s);
}
catch(Exception ex){}
}
}
Scanner Class of java.util package
import java.util.*;
class In_3
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter Your Name: ");
String s=sc.nextLine();
System.out.println("Your name is "+s);
System.out.print("Enter Your Name: ");
String s1=sc.nextLine();
System.out.println("Your name is "+s1);
}
}
Integer Input using Scanner Class
import java.util.*;
class In_4
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter First Number: ");
int a=sc.nextInt();
System.out.print("Enter Second Number: ");
int b=sc.nextInt();
System.out.println("Sum="+(a+b));
}
}
No comments:
Post a Comment