Using Scanner Class in java & Getting a character

Getting an  input from the user using Scanner class     in java:

      In this tutorial we are gonna see how to accept input from user. We are using Scanner class to get the input. In the below example we are getting input String, integer and a float number. For this we are using following methods:


  1. public String nextLine(): For getting input String
  2. public int nextInt(): For integer input
  3. public float nextFloat(): For float input





Main Class:

import java.util.Scanner;

public class Test
{
 public static void main(String args[])
 {
  int No;
  
  Scanner input = new Scanner(System.in);
  
  System.out.print("\nEnter a Number: ");
  No = input.nextInt();
  
  System.out.println("Entered Number is: " + No);
 }
}

  Getting a Single character from User in java:

   In java we get a String input from the user.For string nextLine() or only next() methods are used.But if we want to get only a character from the user.Then there is some other process for that.
We know that a string is an array of character.So in the case of character first we Convert the string to character array by using toCharArray() method.Then we pick the value at "0" index in char array.So this is our character which we get from the user. 


Main Class:

import java.util.Scanner;

public class Test
{
 public static void main(String args[])
 {
  String ss = "";
  
  Scanner input = new Scanner(System.in);
  
  System.out.print("\nEnter a Character: ");
  ss = input.nextLine();
         char[] arr = ss.toCharArray();
                char ch = arr[0];
  System.out.println("Character is: " +ch);
 }
}

No comments:

Post a Comment