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


// 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 个元素。我很确定我的逻辑是正确的,但是,当我运行代码时,它根本不显示数组。我应该如何解决这个问题?

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

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,并且您的方法只是返回。

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

此外,在toStrng方法中,你可以只使用arrSize而不是IntArray.length

最新更新