Scanner classes

1,910 views

Published on

  • Be the first to comment

Scanner classes

  1. 1. Scannerclasses
  2. 2. Allows the user to input the values of various types Defined within a package java.util This allows the user to input the values from either the keyboard or from file without using any conversion
  3. 3. Importing import java.util.Scanner;
  4. 4. Creating scanner object Scanner sc = new Scanner(System.in);
  5. 5. Methods • nextInt(): • receives the next token from scanner object which can be expressed as an integer and stored in integer type
  6. 6. • nextFloat(): • receives the next token from scanner object which can be expressed as an floating and stored in float type
  7. 7. • nextLong(): • receives the next token from scanner object which can be expressed as an long and stored in long type
  8. 8. • nextDouble(): • receives the next token from scanner object which can be expressed as an double and stored in double type
  9. 9. • next(): • receives the next token from scanner object as a string
  10. 10. • next (): receives the next token from scanner object as a string • nextLine():receives the next line of the string
  11. 11. Ex: int n= in.nextInt(); float f = in.nextFloat(); String s1=in.next(); String s2=in.nextLine(); 19 52.360 Understanding computer Applications Outputs: 68 52.360 Understanding Computer Applications
  12. 12. Program import java.util.Scanner; class scanner1 { void main() { Scanner sc = new Scanner(System.in); int n; double d; String word; String line; System.out.println("Enter int,double,a line"); n=sc.nextInt(); d=sc.nextDouble(); word=sc.next(); line=sc.nextLine(); System.out.println("The outputs are"); System.out.println(n); System.out.println(d); System.out.println(word); System.out.println(line); } }
  13. 13. Output Enter int,double,a line 23 2345.6789 I Love India The outputs are 23 2345.6789 I Love India
  14. 14. Token checking methods • Boolean hasNextInt() • Returns true if the next token in the scanner object can be interrupted as an int value
  15. 15. • Boolean hasNextLong() • Returns true if the next token in the scanner object can be interrupted as a long value
  16. 16. • Boolean hasNextFloat() • Returns true if the next token in the scanner object can be interrupted as a float value
  17. 17. • Boolean hasNextDouble() • Returns true if the next token in the scanner object can be interrupted as a double value
  18. 18. • Boolean hasNext() • Returns true if the scanner object has another token in its input otherwise false
  19. 19. • Boolean hasNextLine() • Returns true if the scanner object has another line in its input otherwise false

×