以下是我正在尝试制作的程序的步骤
.toCharArray()
但是这个数组给了我一个空指针异常。我究竟做错了什么? (忽略班级命名我知道这很愚蠢,但我必须这样做,因为我的老师想要那样)
主要课程:
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];
}
}
}
答案 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;
}
}