简体   繁体   中英

Why do I need to add + 1 to this array in Java?

I'm looking at this piece of code I found and hopefully someone can help me. The program takes two numbers and prints to the screen what is in between the the two numbers, so for example 20 and 15 would print

[15, 16, 17, 18, 19, 20]

I want to know why the person would wrote the code decided to add 1 to the array here:

int[] range = new int[(upper - lower + 1)]; 

if you were to leave the +1 out the print statement would only produce

[15, 16, 17, 18, 19]

Hopefully someone can help me out.

Actual desired program output : The array: [ 15 16 17 18 19 20 ]

public class RangeLister {

    int[] makeRange(int lower, int upper) {

        int[] range = new int[(upper - lower + 1)];

        for (int i = 0; i < range.length; i++) {
            range[i] = lower++;
        }
        return range;
    }

    public static void main(String[] arguments) {
        int[] range;
        RangeLister lister = new RangeLister();

        range = lister.makeRange(15, 20);
        System.out.print("The array: [ ");
        for (int i = 0; i < range.length; i++) {
            System.out.print(range[i] + " ");
        }
        System.out.print("]");
    }
}

Because you want your range to be inclusive.

If you left the +1 out, you would have 20-15 = 5 . However, you want to include 20 and 15, so you need an extra digit. Just count them:

15, 16, 17, 18, 19, 20

That's 6 digits (20-15+1) , not 5 digits (20-15) .

The range needs to be inclusive if you want to print the first integer and every integer inbetween including the last integer. Adding the +1 makes the range inclusive.

It's easier to see with a smaller range like [1, 2] .

You want to print:

1 2

Without adding the +1 the range would be

range = 2 - 1 = 1

Which means that in your for loop, you would only call the print 1 time. This would result in an output of:

1

By adding the +1 you are including the last number so your range is:

range = 2 - 1 + 1 = 2

Now, in your for-loop, you will print 2 numbers and your ouput will be

1 2 

That's because there are actually 6 numbers from [15,20] . The difference of these numbers would only give 5 which will not print numbers up to the greater number ie 20. Adding +1 solves the problem.

You need the value of range to be 6. so that it can iterate/pick 15 to 20.

Take the following statement. where upper=20 and lower=15 .

int[] range = new int[(upper - lower + 1)]; 
range= 20-15+1 = 6

if you do just `int[] range = new int[(upper - lower)];

range= 5. you miss the number '20'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM