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

时间:2016-03-03 05:01:23

标签: java

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;
    }           
}

提供的程序正常工作,但我没有非常整洁/专业地编写它。任何人都可以给我一些关于我如何重写这个以在列表类下实现面向对象编程的指导?

7 个答案:

答案 0 :(得分:2)

这可以是另一种选择......

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] + "  ");
    }
}

或类似的东西......

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;
    }           
}

朋友,有很多选择。

答案 1 :(得分:0)

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()); 

这是你想要的吗?

答案 2 :(得分:0)

  

structured linear中编写此oops程序的多种方法。这是我的版本..

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;
    }           
}
  

将业务逻辑与其他类分开的另一种方法。并从别人那里打电话。

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();

        }
}

答案 3 :(得分:0)

您可以使用Random(和nextInt(int)),以及Java 8+ lambda expression。这可能看起来像

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);
});

答案 4 :(得分:0)

使用列表:

以下是使用对象列表来保存每个数字的示例类。您可以使用参数化构造函数声明最大大小,也可以使用默认构造函数将其设置为100。

setNumbers方法永远不会执行多次(通过检查大小到最大大小),以便列表永远不会大于最大大小。此外,您可以向setNumbers方法添加参数,以便您可以选择每个随机数之间的范围,而不仅仅是10-99。 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));


}



}

以下是驱动程序类的示例。

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();
    }


}

答案 5 :(得分:0)

您可以创建自己的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);
    }
}

答案 6 :(得分:0)

您可以实现自己的List类。为此,您应该定义一个Node,一个List类(包含节点)和一个负责创建随机数的服务。

此服务将以单例(一个无法由任何其他类实例化的类)表示。

    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;
        } 

    }

节点将只包含一个值(随机数)和对下一个节点的引用。这是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;
        }
    }

List类将包含对根节点的引用,该节点还负责将新节点添加到列表中。

请记住,您也可以使用Generics。

    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());
            }
        }

    }

Main必须只实例化MyList类并调用printList来显示列表。

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

希望这会对你有所帮助。