简体   繁体   中英

How can I rewrite this code to use object oriented programming?

public class stackOverflow
{
    public static void main (String args[])
    {
        int maxNumbers = 100;
        int numbers[] = new int[maxNumbers];
        for (int k = 0; k < numbers.length; k++)
            numbers[k] = getRandom(10,99);
        for (int k = 0; k < numbers.length; k++)
            System.out.print(numbers[k] + "  ");
        System.out.println(); 
    }
    public static int getRandom(int min, int max)
    {
        int range = max - min + 1;
        double rndDouble = Math.random() * range;
        int rndInt = (int) rndDouble + min;
        return rndInt;
    }           
}

The provided program works correctly, but I didn't write it very neatly/professionally. Can anyone give me some guidance on how I could rewrite this to implement Object Oriented Programming under a List class ?

This can be an alternative...

class Numbers {
    int maxNumbers;
    int numbers[];
    public Numbers(int maxNumbers) {
        // TODO Auto-generated constructor stub
        this.maxNumbers = maxNumbers;
        this.numbers = new int[maxNumbers];
    }
    public int getRandom(int min, int max) {
        int range = max - min + 1;
        double rndDouble = Math.random() * range;
        int rndInt = (int) rndDouble + min;
        return rndInt;
    } 
}
public class StackOverflow {
    public static void main(String [] args) {
        Numbers numbers = new Numbers(100);
        for (int k = 0; k < numbers.numbers.length; k++)
            numbers.numbers[k] = numbers.getRandom(10,99);
        for (int k = 0; k < numbers.numbers.length; k++)
            System.out.print(numbers.numbers[k] + "  ");
    }
}

Or something like this...

public class StackOverflow {

    static int maxNumbers = 100;
    static int numbers[] = new int[maxNumbers];

    public static void main (String args[]) {
        StackOverflow stackOverflow = new StackOverflow();

        for (int k = 0; k < numbers.length; k++)
            numbers[k] = stackOverflow.getRandom(10,99);
        for (int k = 0; k < numbers.length; k++)
            System.out.print(numbers[k] + "  ");
        System.out.println(); 
    }

    public int getRandom(int min, int max) {
        int range = max - min + 1;
        double rndDouble = Math.random() * range;
        int rndInt = (int) rndDouble + min;
        return rndInt;
    }           
}

Friend, There are a numbers of alternatives.

import java.util.ArrayList;
import java.util.List;    

int maxNumbers = 100;
List<Integer> numbers = new ArrayList<Integer>();
for (int k = 0; k < maxNumbers; k++)
    numbers.add( getRandom(10,99) );

System.out.println(numbers.toString()); 

is this kind of what you wanted?

A Number of ways to write this structured linear program in oops . Here is my version..

public class stackOverflow
{
    int numbers[];

     public stackOverflow(){   //assuming default constructor will provide a 100 length array
      int maxNumbers = 100;
      this.numbers[]  = new int[maxNumbers];
     }

     public stackOverflow(int length){ //Provide a length according to your need.
         this.numbers[] = new int[length];
     }

    private void fillNumberArrayWithRandomNumber(){
    for (int k = 0; k < this.numbers.length; k++)
            numbers[k] = this.getRandom(10,99);
    }

    private void printAllNumbersInArray(){
           for (int k = 0; k < this.numbers.length; k++)
            System.out.print(numbers[k] + "  ");
        System.out.println(); 
    }

    public static void main (String args[])
    {
        stackOverflow obj1 = new stackOverflow(); //default Constructor will call with array lenth 100
        obj1.fillNumberArrayWithRandomNumber();
        obj1.printAllNumbersInArray();

       stackOverflow obj2 = new stackOverflow(50);  //overloaded Constructor will Call with array length 50
        obj2.fillNumberArrayWithRandomNumber();
        obj2.printAllNumbersInArray();

    }
    public int getRandom(int min, int max)
    {
        int range = max - min + 1;
        double rndDouble = Math.random() * range;
        int rndInt = (int) rndDouble + min;
        return rndInt;
    }           
}

Another Way to separate the business logic to the other class. and calling it From Others.

public class GenerateRandomNumbers
    {
        int numbers[];

         public GenerateRandomNumbers(){   //assuming default constructor will provide a 100 length array
          int maxNumbers = 100;
          this.numbers[]  = new int[maxNumbers];
         }

         public GenerateRandomNumbers(int length){ //Provide a length according to your need.
             this.numbers[] = new int[length];
         }

        public void fillNumberArrayWithRandomNumber(){
        for (int k = 0; k < this.numbers.length; k++)
                numbers[k] = this.getRandom(10,99);
        }

        public void printAllNumbersInArray(){
               for (int k = 0; k < this.numbers.length; k++)
                System.out.print(numbers[k] + "  ");
            System.out.println(); 
        }

        private int getRandom(int min, int max)
        {
            int range = max - min + 1;
            double rndDouble = Math.random() * range;
            int rndInt = (int) rndDouble + min;
            return rndInt;
        }           
    }

  class stackOverflow {
     public static void main (String args[])
        {
            GenerateRandomNumbers obj1 = new GenerateRandomNumbers(); //default Constructor will call with array lenth 100
            obj1.fillNumberArrayWithRandomNumber();
            obj1.printAllNumbersInArray();

           GenerateRandomNumbers obj2 = new GenerateRandomNumbers(50);  //overloaded Constructor will Call with array length 50
            obj2.fillNumberArrayWithRandomNumber();
            obj2.printAllNumbersInArray();

        }
}

You could do it with Random (and nextInt(int) ), and in Java 8+ a lambda expression . That might look something like

int maxNumbers = 100;
int min = 10;
int max = 99;
Random rand = new Random();
List<Integer> al = new ArrayList<>();
IntStream.range(0, maxNumbers).forEach(x -> {
    al.add(rand.nextInt(max - min) + min);
});
al.stream().forEach(x -> {
    System.out.printf("%d%n", x);
});

Using a list:

The following is an example class that utilizes an object list to hold each number. You can either declare a max size with the parameterized constructor or you could use the default constructor which sets it to 100.

The setNumbers method will never execute more than once (by checking the size to the max size) so that the list never gets larger than the max size. Also, you could add parameters to the setNumbers method so that you could choose the range that each random number would be between rather than just 10-99. The getNumbers method will return the list object which contains all of the numbers.

import java.util.ArrayList;
import java.util.List;

public class Example {

    int maxNumbers;
    List<Object> list = new ArrayList<Object>();

public Example(){
    this.maxNumbers = 100;
}

public Example( int max){
    this.maxNumbers = max;
}

private int getRandom(int min, int max)
{
    int range = max - min + 1;
    double rndDouble = Math.random() * range;
    int rndInt = (int) rndDouble + min;
    return rndInt;
}  

public List<Object> getNumbers(){
    return this.list;
}

public void setNumbers(){

    if (list.size() >= maxNumbers){
        return;
    } 

    for (int k = 0; k < this.maxNumbers; k++)
        this.list.add(getRandom(10,99));


}



}

Here is an example for a driver class.

public class ExampleDriver
{
    public static void main (String args[])
    {
        //Instantiates the object using the default constructor.
        Example test = new Example();

        //Generates the numbers within the list.
        test.setNumbers();

        //Stores the returned list from getNumbers() to exampleList
        List<Object> exampleList = test.getNumbers();
    }


}

You can create your own RandomList which extends ArrayList<Integer> :

public class RandomList extends ArrayList<Integer> {
    private int size;
    private int min;
    private int max;
    public RandomList(int size, int min, int max) {
        super(size);
        this.size = size;
        this.min = min;
        this.max = max;
    }

    /**
     * Populate list with entries between min and max
     */
    public void populate() {
        Random rand = new Random();
        for (int t = 0; t < size; t++) {
            this.add(rand.nextInt(max - min) + min);
        }
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Integer i:this) {
            sb.append(i).append(" ");
        }
        return sb.toString();
    }

    public static void main (String [] args) {
        RandomList randomList = new RandomList(100, 10, 99);
        randomList.populate();
        System.out.println(randomList);
    }
}

You could implement your own List class. For that you should define a Node, a List class (which will contain nodes) and a Service that will be responsible to create the random numbers.

This service will be represented in a singleton (a class that cannot be instantiated by any other class).

    public class MyRandom {

        private static MyRandom rdn = new MyRandom();

        private MyRandom() {}

        public static MyRandom getInstance() {
            return rdn;
        }

        public int getRandom(int min, int max) {
            int range = max - min + 1;
            double rndDouble = Math.random() * range;
            int rndInt = (int) rndDouble + min;
            return rndInt;
        } 

    }

The Node will only contain a value (the random number) and a reference to the next node. This is the Node class

    public class MyNode {

        private final int value;
        private MyNode next;

        public MyNode(int value) {
            this.value = value;
            next = null;
        }

        public void setNext(MyNode next) {
            this.next = next;
        }

        public int getValue() {
            return value;
        }

        public MyNode getNext() {
            return next;
        }
    }

The List class will contain a reference to the root node, which will also be responsible to add new nodes to the list.

Keep in mind that you could use Generics as well.

    public final class MyList {

        private MyNode root;

        public MyList(int maxNumber) {
            for (int i = 0; i < maxNumber; i++) {
                addNode(MyRandom.getInstance().getRandom(0, 99));
            }
        }

        public boolean isEmpty() {
            return root == null;
        }

        public void addNode(int value) {
            if (isEmpty()) {
                root = new MyNode(value);
            } else {
                MyNode aux = root;

                while (aux.getNext() != null)
                    aux = aux.getNext();

                aux.setNext(new MyNode(value));
            }
        }

        public void printList() {
            if (!isEmpty()) {
                MyNode aux = root;
                while (aux.getNext() != null) {
                    System.out.println(aux.getValue());
                    aux = aux.getNext();
                }  
                System.out.println(aux.getValue());
            }
        }

    }

And the Main must only instantiate the MyList class and call the printList to show the list.

    public class Main {
        public static void main(String[] args) {
            MyList lista = new MyList(10);
            lista.printList();
        }
    }

Hope this helps you.

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