简体   繁体   English

如何重写此代码以使用面向对象的编程?

[英]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 ? 谁能给我一些指导,以指导我如何重写它以实现List类下的面向对象编程?

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 . oops编写这种structured linear程序的许多方法。 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 . 您可以使用Random (和nextInt(int) ),并在Java 8+中使用lambda表达式 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. 您可以使用参数化构造函数声明最大大小,也可以使用将其设置为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. setNumbers方法永远不会执行一次以上(通过将大小检查为最大大小),以使列表永远不会大于最大大小。 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. 另外,您可以向setNumbers方法中添加参数,以便可以选择每个随机数介于10至99之间的范围。 The getNumbers method will return the list object which contains all of the numbers. getNumbers方法将返回包含所有数字的列表对象。

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> : 您可以创建自己的RandomList来扩展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. 您可以实现自己的List类。 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. 为此,您应该定义一个Node,一个List类(将包含节点)和一个Service来创建随机数。

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 这是Node类

    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. 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. Main必须仅实例化MyList类并调用printList来显示列表。

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

Hope this helps you. 希望这对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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