please explain me the input programs in java with examples.No spamming .Correct answers because I'm spending 50 points.
Answers
Here is your Answer:
Java program to get input from a user: we are using Scanner class to get input from the user. This program asks the user to enter an integer, a float, and a string; then they are printed on the screen. Scanner class is present in java.util package so we import this package into our program. We first create an object of Scanner class and then we use the methods of Scanner class. Consider the statement
Scanner a = new Scanner(System.in);
Java input program
import java.util.Scanner;
class GetInputFromUser
{
public static void main(String args[])
{
int a;
float b;
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered integer " + a);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float " + b);
System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string " + s);
}
}
I hope this helped you
Hi mate,
- Answer : Java Scanner class allows the user to take input from the console. It belongs to java.util package. It is used to read the input of primitive types like int, double, long, short, float, and byte. It is the easiest way to read input in Java program.
- The above statement creates a constructor of the Scanner class having System.inM as an argument. It means it is going to read from the standard input stream of the program. The java.util package should be import while using Scanner class.
- It also converts the Bytes (from the input stream) into characters using the platform's default charset.
Example of integer input from user
import java.util.*;
class UserInputDemo
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter first number- ");
int a= sc.nextInt();
System.out.print("Enter second number- ");
int b= sc.nextInt();
System.out.print("Enter third number- ");
int c= sc.nextInt();
int d=a+b+c;
System.out.println("Total= " +d);
}
}
i hope it helps you.