PDA

View Full Version : Java ask forum


Lonerli
May 15, 2013, 05:59 AM
Hey Guys, please I need help badly. Thank You

I read a text file from my hard disk which contains as follows...

void main()
{
int A = 5;
int B = 5;
int C ;
C = A + B;
cout << C ;
}

So, what I need to do is that..
Lets say I have an array of...

String []KeyWord = {"void", "main()"};
String []DataType = {"int", "float"};

So I want to loop through each token and check whether for example it's a key word or a datatype. I used java netBeans and I code as follows


int k = 0; int l = 0;

StringTokenizer Tokens;

while ((CurrentLine = ReadFile.readLine()) != null)
{
Tokens = new StringTokenizer(CurrentLine, " ", true);
for (int I = 0; Tokens.hasMoreTokens(); I++)
{
if (Tokens.nextToken().contains(KeyWord[k]))
{
jTextArea1.append(KeyWord[k] + "\n");
k++;


}
else if (Tokens.nextToken().contains(DataType[l]))
{
jTextArea2.append(DataType[l] + "\n");

}

}
}

I RECEIVE ERRORS I DON'T UNDERSTAND. PLEASE HELP ME GUYS THANKS...

jstrike
May 29, 2013, 08:15 AM
You don't say what version of java you're using, I would recommend 7 if you can. What I would do is create a subclass of ArrayList as follows:

public class MyArrayList<E extends Object> extends ArrayList<E> {
private static final long serialVersionUID = 1L;

@SuppressWarnings("unchecked")
public MyArrayList(Object[] array) {
for(Object o : array)
this.add((E) o);
}
}

You would then read a line in from your text file and split it on the spaces as follows:


try (Scanner in = new Scanner(new FileReader("/mytextFile.txt"))){

while(in.hasNext()) {

String[] line = in.nextLine().split(" ");
List<String> line = new MyArrayList<String>(line);

for(String kWord : KeyWord) {
if(line.contains(kWord)) {
//...do processing
break;
}
}
for(String dType : DataType) {
if(line.contains(dType)) {
//...do processing
break;
}
}
}
} catch(FileNotFoundException fnfe) {
fnfe.printStackTrace();
}


Hope this helps.