Home > database >  Trying to use the outcome of first method in second method java
Trying to use the outcome of first method in second method java

Time:12-18

I am trying to learn how can I use the outcome of one method in another method.

In example below it creates an ArrayList of integers from 1 to 50 and then takes an absolute value of random two values from the ArrayList of integers, then adds this absolute value to the list (named boardIntegers), but removes the selected random two numbers.

This is repeated 49 times.

I have solved it by creating one method and then calling that method from main method.

Can I solve by creating two methods, for example one for creating the list boardIntegers and the other for updating boardIntegers?

package ProblemAllocated;  

import java.util.ArrayList;
import java.util.Random;

public class Board {

    public static void main(String[] args) {
        UpdateBoard();
        //method2();
    }
    
    public static void UpdateBoard() { 
        int a;
        int b;
        int AbsC;
        ArrayList <Integer>boardIntegers = new ArrayList<>();
        Random fromBoard = new Random();

        for (int i = 1; i < 51; i  ) {
            boardIntegers.add(i);
        }

        for (int i = 0; i < 50; i  ) {
            a = fromBoard.nextInt((boardIntegers.size()));
            b = fromBoard.nextInt((boardIntegers.size()));
            AbsC = Math.abs(b - a);
            boardIntegers.add(AbsC);
            boardIntegers.remove(a);
            boardIntegers.remove(b);
            System.out.println("The remaining integers after executing " 
                  i   " times are "   boardIntegers 
                  " and size of List is "   boardIntegers.size()
            );
        }
    }
}

CodePudding user response:

EDIT

Sorry, misunderstood. As Dave Newton is trying to say, your first method could create the collection, and return it, which in turn can be passed on to the next method that updates it.

E.g.

int boardSize = 50;
ArrayList<Integer> board = createBoard(boardSize);
updateBoard(board);

Hope you understand, and you'll have to implement the methods yourself. :-)

Side note. The variable board is passed as value. This means the reference to the object is copied and passed, not the object itself. So if you try to overwrite board inside updateBoard you will overwrite the copied reference, with a another reference pointing to another object, and not the original reference, nor the original object. But the copied reference points to the original object, which means calling methods using the copied referenced, will call methods on the original object and thus impact the original object, e.g. board.remove(a) inside updateBoard, will change the the board object from main.

END EDIT

Yes - you can either create a local variable in main, and pass it as a parameter to each method, or create a global variable which you use in both methods.

Hope it makes sense. :-)

CodePudding user response:

Yes, use multiple smaller methods

Can I solve by creating two methods, for example one for creating the list boardIntegers and the other for updating boardIntegers?

Yes, you can. And you should. Better to have smaller chunks of code with a specific narrow purpose, segregated into well-named methods.

You will see in the code below that we broke out your code into two principal methods:

  • a constructor
  • a method named randomize

OOP

I think the bigger picture you are missing is object-oriented programming (OOP).

Your Board class should represent a board, describing a board from real life. A board has characteristics/attributes, in your case here, a size and set of integers (which I am guessing represents slots or positions on the board). So your class should represent those attributes as state, as member field variables.

public class Board
{
    // Member fields.
    final private int boardSize;
    final private List < Integer > slots;
…

Get the basics of your board’s state ready in a constructor. Generally best to keep your constructor as short and as simple as possible. The goal is to do the least necessary to leave the object in a coherent state.

In our case here, perhaps the constructor should just establish the slots with the default 1, 2, 3, … sequencing. Our constructor takes one parameter, the size (50), as that is likely to be the one aspect of the board you are likely to change (my assumption).

// Constructor
public Board ( final int boardSize )
{
    this.boardSize = boardSize;
    this.slots = new ArrayList <>( this.boardSize );
    // Populate the slots with sequential numbers, one through count of slots.
    for ( int nthSlot = 1 ; nthSlot <= this.boardSize ; nthSlot   )
    {
        this.slots.add( nthSlot );
    }
    // Or more briefly, using streams:
    // this.slots = new ArrayList <>( IntStream.rangeClosed( 1 , this.boardSize ).boxed().toList() );
}

Your goal is to randomize the slots of the board. So create a method randomize to do that work.

I question the logic of your code for the randomizing, but that code is not relevant to the point of your Question. So let’s skip that code, and simply replace each slot’s value with the result of a call to ThreadLocalRandom.current().nextInt.

private void randomize ( )
{
    for ( int index = 0 ; index < this.boardSize ; index   )
    {
        int absC = ThreadLocalRandom.current().nextInt( 1_000 );
        this.slots.set( index , absC );
    }
}

We need a way to examine our board object. So we add another method, this one named report.

private void report ( )
{
    System.out.println( "this.slots = "   this.slots   " at "   Instant.now() );
}

  • Related