2017-05-28 223 views
-3

我在下面有一个测试类,它调用我的shuffle类,该类创建随机数的ArrayList并对它们进行排序。当我从测试类中调用这个ArrayList时,什么都不会发生。无法填充ArrayList

static ArrayList yup = new ArrayList(); 

public static void main(String[]args){ 


    Scanner input = new Scanner(System.in); 
    System.out.println("Enter a num to create a random list of numbers: "); 
    int guess = input.nextInt(); 
    shuffle y = new shuffle(guess); 
    System.out.println(y.toString()); 
    ArrayList<Integer> jh = y.getnew_list(); 
    for(int d = 0; d < jh.size();d++){ 
    //System.out.println(three.get(d)); 
    System.out.println(jh.get(d)); 
    } 
    shuffle one = new shuffle(guess); 

    } 
随机

类========================

import java.util.*; 

import java.util.Random; 

public class shuffle implements Comparable <shuffle> { 

    static int size; 

    static ArrayList new_list = new ArrayList(); 

    shuffle(int size){ 
    this.size = size; 
    Random rand = new Random(); 

    for(int i = 0; i<new_list.size();i++){ 
    int t = rand.nextInt(50) + 1; 
    new_list.add(t);   

    } 

}

public ArrayList getnew_list(){ 
    return this.new_list; 

}

public int getSize(){ 

    return size; 

}

public String toString(){ 
     String str = new String(); 
     for(int i = 0; i<new_list.size();i++){ 
    str += " " + new_list.get(i); 
    System.out.println(str); 


    } 

    return str; 

}

public int compareTo(shuffle that){ 

    if(this.getSize() > that.getSize()){ 
    return 1; 
    } 
    if(this.getSize() < that.getSize()){ 
    return -1; 
    } 
    else 
    return 0; 

}

}

+1

发表您的'Shuffle'类 – Kaushal28

+8

邮报[MCVE],并尝试成为比 '什么也没发生' 略知一二。看看[问] – pvg

+0

为什么你有一个shuffle类的构造函数,但它使它成为一个静态字段? – Shane

回答

1
在洗牌类

你没有初始化大小可变,并且使用它作为未初始化的变量可能的原因之一。

import java.util.*; 
 

 
import java.util.Random; 
 

 
public class shuffle implements Comparable <shuffle> { 
 

 
    static int size; 
 

 
    static ArrayList new_list = new ArrayList(); 
 

 
    shuffle(int size){ 
 
    this.size = size; 
 
    Random rand = new Random(); 
 

 
    for(int i = 0; i<new_list.size();i++){ 
 
    int t = rand.nextInt(50) + 1; 
 
    new_list.add(t);