Do you think I am crazy?

Please take a look at the following sample:

import java.util.Scanner;

public class Client{

public final static int LIMIT = 2000;

public static void main(String[] args){

int cur = 1000;

Scanner input = new Scanner(System.in);

System.out.print(“please give me a number”);

while(input.hasNextInt()){

int order = input.nextInt();

if(order>0 && order+cur<=LIMIT){

System.out.println(“You have booked “+order+”products.”);

}else{

System.out.println(“Exceed the limitation”);

}

}

}

}

Run it. You type 100, then the answer is You have booked 100 products. OK it is my expectation.

You type 3000, then the answer is Exceed the limitation. OK it is my expectation.

Please try 2147483647! What is your expectation? Exceed the limitation! Apparently 2147483647 is greater than 2000. BUT the result is You have booked 2147483647 products.

Your computer got a virus? No. What is 2147483647? 2147483647 is the max number of the int type within Java. So when this MAX number is added to 1000 it becomes -2147482649 which is a negative number. Any negative number is lower then 2147483647. That makes sense.

Thus when we are testing a method with int as a parameter, please test THREE things, the min number of int, the max number of int and then ZERO.

### Like this:

Like Loading...

*Related*