Add numbers in array without adding adjacent number

Posted on

Problem

This is first time I code reviewing and would like feedback on coding in industry standards and optimum code.

This program adds number in array in two formats:

  1. Adds adjacent numbers in a serial manner as proof for the actual sum to refer to the required output.
  2. Adds the last and first variables in the array.
import java.util.stream.IntStream;

class  twoadj1
{
    public int a;
    public int b[];
    public int sum=0;
    public int sum1=0;
    public int k=0;
    public int m=0;
    twoadj1(int size)
    {
    b = new int[size];
    k = size-1;
    m = size;
    }
    void valueadd()
    {
        {

        for(int z = 0; z < b.length; z++) {
            b[z] = (int)(Math.random()*9);

        System.out.print(b[z]+ " ");
        int sum = IntStream.of(b).sum();
        System.out.println("real sum"+sum);
        }
        for (int j=0;j<b.length/2;j++)

            {

        sum1 = sum1+b[j]+b[k];
        k--;
        System.out.println("Process: " +sum1);
            }
        if((m%2)==0)
            System.out.println("Sum after required output1: " +sum1);
            else if((m%2)==1) 
            {
            sum1 += b[m/2];
            System.out.println("Sum after required output2: "+sum1);
            }


        }
    }
}

public class twoadj {
    public static void main(String[] args) 
    {
    twoadj1 a = new twoadj1(5);
    a.valueadd();
    }
}

Solution

Your indentation is inconsistent, and it looks like you got confused yourself, since you are computing and printing “real sum” many times.

The code organization could use improvement as well. The valueadd() function does a lot of stuff:

  • Populating the array with random members
  • Printing the array
  • Summing the array using streams, and printing that sum
  • Summing the array by working from the ends towards the middle, and printing that sum

There is no way to figure out what it does without reading all of the code. Ideally, each function should be limited to a single responsibility.

There are a lot of instance variables, all cryptically named, and all public:

public int a;
public int b[];
public int sum=0;
public int sum1=0;
public int k=0;
public int m=0;

Only the array should be an instance variable here; all of the others could be local variables.

The output looks a bit sloppy as well. For example, I would expect there to be a newline after printing the array contents, and a space after "real sum".

Suggested solution

Notice how each method has a one-sentence JavaDoc summary of what it does. (If you can’t write such a summary for a function, then it would be an indication that the function is poorly designed.)

import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class ArrayAdder {
    private int[] array;

    /**
     * Randomly populates an array of integers of the specified size.
     */
    public ArrayAdder(int size) {
        this.array = new int[size];
        for (int i = 0; i < size; i++) {
            this.array[i] = (int)(9 * Math.random());
        }
    }

    /**
     * The elements of the array, delimited by spaces.
     */
    public String toString() {
        return IntStream.of(this.array)
                        .mapToObj(String::valueOf)
                        .collect(Collectors.joining(" "));
    }

    /**
     * Sums the array using IntStream.
     */
    public int streamSum() {
        return IntStream.of(this.array).sum();
    }

    /**
     * Sums the array by working from the ends toward the middle.
     */
    public int nestedSum() {
        int i, j, sum = 0;
        for (i = 0, j = this.array.length - 1; i < j; i++, j--) {
            sum += this.array[i] + this.array[j];
        }
        if (i == j) {
            sum += this.array[i];
        }
        return sum;
    }

    /**
     * Demonstrates the equivalence of two addition methods on a 5-element array.
     */
    public static void main(String[] args) {
        ArrayAdder demo = new ArrayAdder(5);
        System.out.println(demo);
        System.out.println("Sum using stream: " + demo.streamSum());
        System.out.println("Nested sum: " + demo.nestedSum());
    }
}

BRACES:

Your braces placement needs to be more consistent. If you decide to put open braces on their own line, or along with the statement, stick with the desired method all the way through the project.

Braces formatting visual:

twoadj1(int size)
{
    b = new int[size];
    k = size-1;
    m = size;
}

twoadj1(int size) {
    b = new int[size];
    k = size-1;
    m = size;
}

Note: The second format is more commonly used throughout java. (From my experience anyway.)

Not placing the “optional” braces in the below code is generally frowned upon.

if((m%2)==0)
    System.out.println("Sum after required output1: " +sum1);  

This style may make it difficult for others to come in behind you with the interest of adding to the if statement block.

When editing someone else’s code, stick with the already chosen braces format, even if you do not agree with the format.

INDENTATION:

Also, not sure if this was the result of copy and paste, but your indentations make it very hard to read your code. Indent at open curly braces like so:

void valueadd()
{
    for(int z = 0; z < b.length; z++) 
    {
        b[z] = (int)(Math.random()*9);

        System.out.print(b[z]+ " ");
        int sum = IntStream.of(b).sum();
        System.out.println("real sum"+sum);
    }

    for (int j=0;j<b.length/2;j++)
    {
        sum1 = sum1+b[j]+b[k];
        k--;
        System.out.println("Process: " +sum1);
    }

    if((m%2)==0) 
    {
        System.out.println("Sum after required output1: " + sum1);
    }
    else if((m%2)==1)
    {
        sum1 += b[m/2];
        System.out.println("Sum after required output2: "+sum1);
    }
}

Note: I removed a set of curly braces due to them having no purpose.

There is much more to improve on, but ill let someone else cover those topics.

Leave a Reply

Your email address will not be published. Required fields are marked *