Nullpointer
Nullpointer

Reputation: 1086

What is the best way to read a file in Java?

I am writing a JAVA program to simulate assembler (as an assignment in my college).

I have an assembly program which is given as an input to this assembler.

The general format of every statement in assembly code is as follows:

[Label] OPCODE OPERAND1 [OPERAND2] (each term separated by a space)

Label and OPERAND2 are optional parts so in some statements these may be unavailable.

In my java code I read each line and then use StringTokenizer to get the 4 parts separated by spaces.

My question is whenever Label AND/OR OPERAND2 are not available how can I find out that the first values returned by StringTokenizer is actually OPCODE value and similarly second value is OPERAND1 value? What is the best way to do this?

Thanks a lot

Upvotes: 0

Views: 363

Answers (2)

Roudy Tarabay
Roudy Tarabay

Reputation: 449

Parse the line and put it in an ArrayList. If ArrayList.size() is 4 than you have all the 4. If it is 3 than test ArrayList.get(0) if it is an Op than the label is unavailable,if it is not than than operand 2 is unavailable. If size is 2 than both label and operand 2 are unavailable. I suggest you make a class for each format(I format,R format...)

Upvotes: 0

clay
clay

Reputation: 6017

If

  1. a Label can never be an OPCODE,
  2. and depending how many OPCODE values exist,

you might just create a method isOpcode(String s) and test the first part after Tokenizing. If it passes, Label must have been missing. If it fails, Label must exist.

Depending on the results of that test, you can count the remaining parts to determine if OPERAND2 is present.

Upvotes: 2

Related Questions