Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

small problem with this code

  Asked By: Maria    Date: Nov 06    Category: Java    Views: 961
  

This may be quite silly but please help me
Whenever any keyboard event occurs the string s gets appended by a,c
or p.At the end of the program its supposed to print value of s
But s always happens to null.Please tell me how to correct it....so
that detection is possible for any case

import java.io.*;
import java.awt.event.*;

public class trial {
int x;
public static String s;

//OutputStream f1=new FileOutputStream("file2.txt");

public static void keyReleased(KeyEvent e)
{
s=s+"a";

}
public static void keyPressed(KeyEvent e)
{
s=s+"c";
}
public static void keyTyped(KeyEvent e)
{
s=s+"p";
}




public static void main(String args[])
throws IOException
{
char c;
BufferedReader br =new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Entercharactes,'q' to quit.");
do
{
c=(char)br.read();
System.out.println(c);
}
while(c!='q');

// for(int i=0;i<s.length();++i)
System.out.println(s);
}
}

Share: 

 

1 Answer Found

 
Answer #1    Answered By: Kiet Jainukul     Answered On: Nov 06

There are several problems with your code:

First of all, events are handled by attaching a listener to an object which
fires specific events. You cannot listen to
events which are generated from the command line. Your keyReleased(),
keyPressed() and keyTyped() methods are never
called which is why the String is always null.

Second, Strings are not mutable in Java. You should use a StringBuffer instead.


Since you can't listen to key events fired from the command line (because key
events aren't fired from the command
line), if you want to create a String with all of your characters, then you
would have to it at:

c=(char)br.read();

Here is an example:


import java.io.*;

public class  IOTest {

public static  StringBuffer s = new StringBuffer();

public static void  main(String args[])
throws IOException
{
char c;
BufferedReader br =new  BufferedReader(new
InputStreamReader(System.in));
System.out.println("Entercharactes,'q' to quit.");
do
{
c=(char)br.read();
s.append(c);
}
while(c!='q');

System.out.println(s.toString());
}
}

 
Didn't find what you were looking for? Find more on small problem with this code Or get search suggestion and latest updates.




Tagged: