使用for循环将数组复制到另一个数组中

时间:2013-04-29 16:20:01

标签: java arrays for-loop copy stack

以下是我正在尝试制作的程序的步骤

  1. 使用扫描仪捕获字符串
  2. 将该String传递给另一个类
  3. 中的方法
  4. 使用.toCharArray()
  5. 将该String的字符分隔为数组
  6. 使用for循环将该数组的内容复制到另一个数组
  7. 但是这个数组给了我一个空指针异常。我究竟做错了什么? (忽略班级命名我知道这很愚蠢,但我必须这样做,因为我的老师想要那样)

    主要课程:

    import java.util.Scanner;
    public class _01 {
    
    
        public static void main(String[] args) {
    
            Scanner input = new Scanner(System.in);
            System.out.print("Enter your name : ");
            String name = input.nextLine();
            int size = name.length();
    
            _02 process = new _02(size);
    
            process.push(name);
    
        }
    
    }
    

    使用数组的其他类:

        public class _02 {
    
            int maxsize;
            int top;
            char arrayStack[];
    
            public _02(int size) {
    
                maxsize = size;
                top = -1;
    
                }
    
            public void push(String letters) {
    
                char temp[]= letters.toCharArray();
    
                for (int c=0;c<temp.length;c++) {
    
                    temp[c] = arrayStack[++top];
    
                }
    
           }
    
    }
    

3 个答案:

答案 0 :(得分:1)

您的作业相反 - 您希望将 temp(作业的右侧)分配到 arrayStack(作业的左侧)。此外,您需要初始化arrayStack,例如arrayStack = new char[temp.length] - 现在它是空的。

答案 1 :(得分:0)

char arrayStack[]; // this is not initialized.


arrayStack[] = new char[temp.length] // inside the push() method.

答案 2 :(得分:0)

数组需要在Java中初始化;简单地声明一个数组会产生一个初始化为null的字段。更改班级以正确初始化arrayStack后,您不需要maxsize字段,因为它与arrayStack.length相同。您还可以使用push方法撤消作业。最后,由于你有一个最大的数组大小,你可能想避免抛出一个ArrayIndexOutOfBoundsException而是抛出一个更有语义意义的异常,或者只是删除多余的字符或增加堆栈(在这种情况下构造函数arg是初始大小)。为此,您需要进行一些范围检查。最后,如果您将top初始化为0而不是-1并使用top++而不是++top(或者更好的是,使用内置API进行复制),则逻辑会更清晰一个阵列的片断。)

public class _02 {
    int top;
    char arrayStack[];

    public _02(int size) {
        arrayStack = new char[size];
        top = 0;
    }

    public void push(String letters) {
        char temp[]= letters.toCharArray();
        int len = temp.length;

        // do some range checking
        if (top + len >= arrayStack.length) {
            // silently ignore the extra characters
            len = arrayStack.length - top;
            // an alternative would be to throw a "stack full" exception
            // yet another alternative would be to grow the stack
        }

//        for (int c=0; c<len; c++) {
//            arrayStack[top++] = temp[c];
//        }
        // don't use a loop--use the API!
        System.arraycopy(temp, 0, arrayStack, top, len);
        top += len;
    }
}