将数组作为字符串打印,每行10个元素

时间:2017-11-15 22:51:56

标签: java arrays

// Line in Main Code 
public class Assignment7 {
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String input;
    char userChoice;
    int newVal, index;
    IntegerList intList = null;

    printMenu();

    do {
        System.out.print("Please enter a command or type? ");
        input = scan.nextLine();
        if (input.length() != 0)
            userChoice = input.charAt(0);
        else
            userChoice = ' ';
        switch (userChoice) {
        case 'a':
            System.out.print("How big should the list be? ");
            intList = new IntegerList(scan.nextInt());
            scan.nextLine();
            System.out.print("What is range of the values for each random draw? ");
            intList.randomize(scan.nextInt());
            scan.nextLine();
            break;
        case 'b':
            System.out.println(intList.toStrng());
            break;

上面的代码是我的主代码的一部分,我获取用户输入,并设置数组的边界条件。案例' b'要求通过调用类中的函数打印出数组,该函数应该将数组作为一个字符串返回,每行10个元素。

// line in class
import java.util.Arrays;
import java.util.Random;
public class IntegerList {

private int arrSize;

public  IntegerList(int size) {
    size = arrSize;
}   

private int[] IntArray = new int[arrSize];

public void randomize (int num) {
    for(int i = 0;i<IntArray.length;i++) {
        IntArray[i] =(int) (Math.random()*(num+1));
    }

}   


public void addElement(int newVal, int index) {
    for(int i = index;i<IntArray.length;i++) {
        int temp = IntArray[i];
        IntArray[i]=newVal;
        IntArray[i+1]=temp;
        if(i == IntArray.length){
            increaseSize(IntArray);
        }
    }

}

private static void increaseSize(int[] x) {
    int[] temp = new int[2*x.length];
    for(int i = 0; i<x.length;i++) {
        temp[i]=x[i];
    }
    x = temp;
}

public void removeFirst(int nextInt) {
    // TODO Auto-generated method stub

}

public String range() {
    // TODO Auto-generated method stub
    return null;
}

public String toStrng() {
    String arrayOut = " ";
    for(int i = 0; i<IntArray.length; i++ ) {
    if(i%10 == 0 ) {
        arrayOut+="\n";
    }

    arrayOut += IntArray[i] + " " ;
    }

    return arrayOut;
}

} 

我试图将数组转换为字符串,然后返回int并让它每行显示10个元素。我非常确定我的逻辑是正确的,但是,当我运行代码时,它根本不显示数组。我该怎么办呢?

2 个答案:

答案 0 :(得分:0)

看看你是如何通过当前的构造函数创建整数数组的......

public  IntegerList(int size) {
    size = arrSize;
}   

private int[] IntArray = new int[arrSize];

致电时

intList = new IntegerList(scan.nextInt());

在您的菜单程序中,您的数组列表不会神奇地知道它需要重新初始化。它将为0,因为在创建IntegerList对象时,arrSize的值始终为0。此外,您还可以切换变量。将构造函数更改为以下

private int[] IntArray = null;

public  IntegerList(int size) {
    arrSize = size;
    IntArray = new int[arrSize];
}

一切似乎都有效,因为数组的大小始终为0而你的方法只是返回。

答案 1 :(得分:0)

您没有初始化 arrSize
您可以修改构造函数以初始化 arrSize
    public IntegerList(int size){     arrSize = size;     }  

此外,在 toStrng 方法中,您只能使用 arrSize 而不是 IntArray.length

相关问题