java - How to avoid null pointer exception in the below code? And Would read() function print a string in the code below? -


for code below compiler gives null pointer exception when using read function. want display, whatever user types, on screen. secondly read function returns int, want display string user types, display string or method have use display string?

//this part in main method. inputstream obj=new task(t); int c;     try {         while((c=obj.read())!=-1){             system.out.print(""+c);         }  //this 1 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 initialized when block executes:

if(e.getkeycode()==e.vk_enter){     content=t.gettext().getbytes();     t.settext(""); } 

to go around this, add check in read method: if(content == null) return -1;

edit:

when override method, should use @override directive. current method, addition of null check, adheres javadoc. if want string value, need add other functionality.

public string getcontent() {      if(content == null)         return "";      return new string(content); } 

however, above depend on how intend use task. option of sort:

public int read(byte[] b, int off, int len) {     if(b == null) return -1;      //use system.arraycopy copy `content` within `b`. } 

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -