Ticker

6/recent/ticker-posts

Java Scanner Class With Example

Scanner Class

Scanner is a class in java. Which is present in java.util package. Scanner is used to scan the input for the program. Scanner will help to scan the input from the keyboard and also we can read the content of the file has a input for the program. 

Scanner scanFromKey = new Scanner(System.in); 

Scanner scanFromFile = new Scanner(new FileReader("vikas.txt")); 

Methods of scanner class

Method Description
byte nextByte() To scan the byte
short nextShort() To scan the short
int nextInt( ) To scan the int, there are also some methods like
nextBigInteger( )
double nextDouble( ) To scan double
float nextFloat( ) To scan the float
String next( ) To scan the string until the space in encountered
String nextLine( ) To scan the entire line until the new line carector
is encountered

Method Returns
boolean hasNextLine() Returns true if the scanner has another line in its
input; false otherwise.
boolean hasNextInt()  Returns true if the next token in the scanner can be
interpreted as an int value.
boolean hasNextFloat() Returns true if the next toke in the scanner can be
interpreted as a float value.


package com.raghu.jspiders; 
import java.util.Scanner
public class ScannerClass 

        public static void main(String[] args) 
        
                 double number; 
                 Scanner in = new Scanner(System.in); 
                 System.out.println("Enter your gross income: "); 
                 if (in.hasNextInt()) 
                 { 
                         number = (double)in.nextInt(); 
                        System.out.println("You entered " + number); 
                 
                 else if (in.hasNextFloat()) 
                 { 
                         number = (double)in.nextFloat(); 
                         System.out.println("You entered " + number); 
                 } 
                 else if (in.hasNextDouble()) 
                 { 
                         number = in.nextDouble(); 
                         System.out.println("You entered " + number); 
                 } 
                 else 
                         System.out.println("Token not an integer or a real value."); 
         

ALSO SEARCH:

"what is scanner class in java with example"

"how to take sentence input in java using scanner class"

"how to input a string in java using scanner class"

"how to get input using scanner class in java"

"how to use the scanner class in java"

"how scanner class works in java"

"what is scanner class in java"

"scanner in java with example"