如何在下面的代码中避免空指针异常? read() 函数会在下面的代码中打印一个字符串吗?
How to avoid null pointer exception in the below code? And Would read() function print a string in the code below?
对于下面的代码,编译器在使用读取函数时给出了一个空指针异常。无论用户输入什么,我都想在屏幕上显示。
其次,读取函数 returns 是一个 int,但我想显示用户键入的字符串,这会显示字符串还是我必须使用任何方法来显示字符串?
//This part is in the main method.
InputStream obj=new Task(t);
int c;
try {
while((c=obj.read())!=-1){
System.out.print(""+c);
}
//This one is another class.
class Task extends InputStream{
byte[] content;
int num=0;
public Task(JTextField t){
t.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e){
if(e.getKeyCode()==e.VK_ENTER){
content=t.getText().getBytes();
t.setText("");
}
super.keyPressed(e);
}
});
}
public int read(){
if(num>=content.length){
return -1;
}
else return content[num++];
}}
content
仅在该块执行时初始化:
if(e.getKeyCode()==e.VK_ENTER){
content=t.getText().getBytes();
t.setText("");
}
要解决这个问题,您可以在 read
方法中添加检查:if(content == null) return -1;
编辑:
重写方法时,应使用@Override
指令。您当前的方法加上空检查,符合 JavaDoc。如果要获取字符串值,则需要添加一些其他功能。
public String GetContent() {
if(content == null)
return "";
return new String(content);
}
但是,以上内容将取决于您打算如何使用任务。另一种选择是:
public int read(byte[] b, int off, int len) {
if(b == null) return -1;
//Use System.Arraycopy to copy `content` within `b`.
}
对于下面的代码,编译器在使用读取函数时给出了一个空指针异常。无论用户输入什么,我都想在屏幕上显示。 其次,读取函数 returns 是一个 int,但我想显示用户键入的字符串,这会显示字符串还是我必须使用任何方法来显示字符串?
//This part is in the main method.
InputStream obj=new Task(t);
int c;
try {
while((c=obj.read())!=-1){
System.out.print(""+c);
}
//This one is another class.
class Task extends InputStream{
byte[] content;
int num=0;
public Task(JTextField t){
t.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e){
if(e.getKeyCode()==e.VK_ENTER){
content=t.getText().getBytes();
t.setText("");
}
super.keyPressed(e);
}
});
}
public int read(){
if(num>=content.length){
return -1;
}
else return content[num++];
}}
content
仅在该块执行时初始化:
if(e.getKeyCode()==e.VK_ENTER){
content=t.getText().getBytes();
t.setText("");
}
要解决这个问题,您可以在 read
方法中添加检查:if(content == null) return -1;
编辑:
重写方法时,应使用@Override
指令。您当前的方法加上空检查,符合 JavaDoc。如果要获取字符串值,则需要添加一些其他功能。
public String GetContent() {
if(content == null)
return "";
return new String(content);
}
但是,以上内容将取决于您打算如何使用任务。另一种选择是:
public int read(byte[] b, int off, int len) {
if(b == null) return -1;
//Use System.Arraycopy to copy `content` within `b`.
}