Home > other >  Modify the java program so that it works for the numbers in range between -25 and 25
Modify the java program so that it works for the numbers in range between -25 and 25

Time:02-06

I've started learning java some time ago. I'm reading through the Java Foundations book and doing exercises from the book to practice.

Just come across this one "Modify the java program so that it works for the numbers in the range between -25 and 25." and I wonder if you have any different solutions to it or is it really that simple? :)

Here's the original code:

public class BasicArray
{
public static void main(String[] args)
{
    final int LIMIT = 15;
    final int MULTIPLE = 10;
    
    int[] list = new int[LIMIT];
    
    // Initialize the array values
    for(int index = 0; index < LIMIT; index  )
        list[index] = index * MULTIPLE;
    
    list[5] = 999; // change one array value
    
    // Print the array values
    for(int value : list)
        System.out.println(value   "");
    }
}

And here's my solution to it:

public class BasicArray
{
public static void main(String[] args)
{
    final int LIMIT = 51;
    final int MULTIPLE = 1;
    
    int[] list = new int[LIMIT];
    
    // Initialize the array values
    for(int index = 0; index < LIMIT; index  )
        list[index] = (index - 25) * MULTIPLE;
    
    list[5] = 999; // change one array value
    
    // Print the array values
    for(int value : list)
        System.out.println(value   "");
    }
}

CodePudding user response:

Yes, basically it's really simple exercise.

Regarding to your solution we actually don't need MULTIPLE in code.

public class BasicArray {

    public static void main(String[] args) {
        final int LIMIT = 51;
    
        int[] list = new int[LIMIT];
    
        // Initialize the array values
        for(int index = 0; index < LIMIT; index  ) {
            list[index] = (index - 25);
        }

        list[5] = 999; // change one array value
    
        // Print the array values
        for(int value : list) {
            System.out.println(value   "");
        }
    }
}

If you are ready for a bit of advanced java, you can try following:

public class BasicArray {
public static void main(String[] args) {
    IntStream.rangeClosed(-25, 25)
        .forEach(System.out::println);
    }
}

Or this if you need to replace one value:

public class BasicArray {
public static void main(String[] args) {
    IntStream.rangeClosed(-25, 25)
        .forEach(i -> {
            if (i == -20) { // change one array value
                System.out.println(999);
            } else {
                System.out.println(i);
            }
        });
     }
}
  •  Tags:  
  • Related