Taking Input with Scanner In Java:
Following methods of Scanner class are used in
the program below :-
1) nextInt to input an integer
2) nextFloat to input a float
3) nextLine to input a string
/* Input From User Using Scanner Class */
This program tells you how to get input from user in a java program. We are using Scanner class to get input from user.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 Input = new Scanner(System.in);
Here Scanner is the class name, Input is the
name of object, new keyword is used to allocate the memory and System.in is the
input stream.
1) nextInt to input an integer
2) nextFloat to input a float
3) nextLine to input a string
/* Input From User Using Scanner Class */
//programming789.blogspot.com/
import java.util.Scanner;
class GetInput {
public static void main(String args[])
{
String s;
int i;
float f;
Scanner Input = new Scanner(System.in);
System.out.println("Enter String Value:");
s = Input.nextLine();
System.out.println("Your Entered Value Is:"+ s);
System.out.println("Your Entered Value Is:"+ s);
System.out.println("Enter Integer Value:");
i = Input.nextInt();
System.out.println("Your Entered Value Is:"+i);
System.out.println("Your Entered Value Is:"+i);
System.out.println("Entered Float Value:");
f = Input.nextFloat();
System.out.println("Your Entered Value Is:"+f);
System.out.println("Your Entered Value Is:"+f);
}
}
● Open notepad and add the code.
● Open notepad and add the code.
● Save the file as GetInput.java.
●Open a command prompt window and go to the directory where you saved the java file.and run following command.
>javac GetInput.java
● Then Run program, When the program is run, the following output is displayed:
>javac GetInput.java
● Then Run program, When the program is run, the following output is displayed:
● Do not declare variable as same as data types. like float float;
● Do not enter wrong value at the time of entering
input. If you enter floating value at integer it will show error.