Assertion in java using scanner method
In this post you learn how can make a java programme using scanner class and how manege data and what is assertion in java and improve quality of your applications!
What is Assertion in Java
According to Sun, we can use assertion to test our assumption about programs. That means it validates our program!
In another words you can say that assertions ensures the program validity by catching exceptions and logical errors.
They can be stated as comments to guide the programmer. Assertions are of two types:
1) Preconditions
2) Post conditions.
Preconditions are the assertions which invokes when a method is invoked and Post conditions are the assertions which invokes after a method finishes.
Where to use Assertions
We can use assertions in java to make it more understanding and user friendly program, because assertions can be used while defining preconditions and post conditions of the
program. Apart from this we can use assertions on internal, control flow and class invariants as well? to improve the programming experience.
Declaring Assertion:
Assertion statements have two form assert
expression;
This statement evaluates expression and throws an Assertion Error if the expression is false.
assert expression1 : expression2
This statement evaluates expression1 and throws an Assertion Error with expression2 as the error message if expression1 is false.
Now we are providing you an example which explains you more clearly.
Here is the source code of Assertion.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package addtwoclass;
import java.util.*;
import java.util.Scanner;
/**
*
* @author rajesh kumar shukla
*/
public class Assertion{
public static void main( String args[] )
{
Scanner scanner = new Scanner( System.in );
System.out.print( "Enter a number between 0 and 20: " );
int value = scanner.nextInt();
assert( value >= 0 && value <= 20 ) :
"Invalid number: " + value;
System.out.printf( "You have entered %d\n", value );
}
}
in this program scanner class read a number from function scanner.nextInt() method and computer accept integer value
form user at command window.and redisplay integer value at command window.If the user entered a number which is out of range then the error occurs.
0 comments:
Post a Comment