Thursday, February 12, 2015

hasNext

In the previous section we have seen that using scanner object and nextInt() we can retrieve the user value and display. Now how to find what type of value is been entered by the user is it int, float or char? Inorder to find that we use hasNextInt(),hasNextFloat(),etc

Below is the simple example which explains the same.

package Example1;
import java.util.Scanner;

public class hasNextInt {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Scanner scanobj=new Scanner(System.in);
  System.out.println("Enter the value");
  if(scanobj.hasNextInt()){ // check if the entered value is integer 
   int result=scanobj.nextInt();
   System.out.println("You have entered "+result);// if true execute the if block
  }
  else{
   System.out.println("Next time enter a integer");// if false execute the else block
  }
  
 }

}

Output:
Enter the value asdasdasd
Next time enter a integer

If you follow the comments it is self explanatory.Instead of hasNextInt(), you can also use hasNextFloat(),hasNextDouble() etc
>>>Math operators
------------------------------------------------------------------------------------------------------------

No comments:

Post a Comment