Assembler

This is basically about assembler (.java) for reading a define file that has extension (.src) and writing it or the output is file extension is (.xxx)... The Assembler has a role during the execuation which are:
1- Invalid opcode
2- Missing opcode
3- Illegal comment
4- Illegal constant
5- Illegal memory address.

I have done so far number 1. 3 and 5 but i want to develop my code and do 2- Missing opcode and 4- Illegal constant...

The code is show below and the main running code is attached
import java.util.Scanner;
import java.lang.String;
 
class Code
{
	private String opcodeSource;
	private String comment;
	private int operand;
	private int opcode;
	private Boolean errorStatus = false;
	private String errorMessage;
	public Code(String codeLine)
	{
		Scanner in = new Scanner(codeLine);
 
		opcodeSource = in.next().trim();
 
		if(!opcodeSource.toLowerCase().equals("stop"))
		{
			if(!opcodeSource.equals(" "))
			{
 
				opcode = inputDecoder(opcodeSource);
				try // this try-catch block is supposed to catch missing opcode but it does not work properly
				{
					operand = in.nextInt();
					comment = in.nextLine().trim();
				}
				catch (Exception e)
				{
					opcodeSource = " ";
					String junk = in.nextLine();
					System.out.println(junk);
					errorStatus = true;
					errorMessage ="Missing opcode";
				}
 
			}
		}
		else  // if opcode is STOP
		{
			operand = 0;
			comment = "; end program";
			opcode = 15;
		}
		if(opcode == 12)  // checks for invalid opcode
		{
			errorStatus = true;
			errorMessage = "Invalid opcode";
		}
		if(!comment.startsWith(";")) //checks for illegal comments
		{
			errorStatus = true;
			errorMessage = "Illegal comment";
		}
		if(opcode == 1 | opcode == 2 | opcode == 3 | opcode == 4 ) // checks for illegal memory address
		{
			if(operand < 0)
			{
				errorStatus = true;
				errorMessage = "Illegal memory address";
			}
		}
	}
 
	public void setOperand(int opcode)
	{
		this.opcode = opcode;
	}
 
	public Boolean getErrorStatus()
	{
		return errorStatus;
	}
 
	public String getErrorMessage()
	{
		return errorMessage;
	}
 
	public String getOpcodeSource()
	{
		return opcodeSource;
	}
 
	public int getOperand()
	{
		return operand;
	}
 
	public String getComment()
	{
		return comment;
	}
 
	public int getOpcode()
	{
		return opcode;
	}
 
	public int inputDecoder(String temp)
	{
		int result;
		temp = temp.toLowerCase();
 
		if(temp.equals("nop"))
			result = 0;
 
		else if(temp.equals("load"))
			result = 1;
 
		else if(temp.equals("store"))
			result = 2;
 
		else if(temp.equals("add"))
			result = 3;
 
		else if(temp.equals("sub"))
			result = 4;
 
		else if(temp.equals("loadi"))
			result = 5;
 
		else if(temp.equals("addi"))
			result = 6;
 
		else if(temp.equals("subi"))
			result = 7;
 
		else if(temp.equals("brz"))
			result = 8;
 
		else if(temp.equals("brn"))
			result = 9;
 
		else if(temp.equals("brp"))
			result = 10;
 
		else if(temp.equals("bra"))
			result = 11;
 
		else if(temp.equals("trap"))
			result = 14;
 
		else if(temp.equals("stop"))
			result = 15;
 
		else
			result = 12;
 
		return result;
	}
}

Open in new window

main.doc
adam_progAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

CEHJCommented:
Please give examples of good input and bad input
0
adam_progAuthor Commented:
i have attached the example
0
adam_progAuthor Commented:
read the file that has exension .src  and the date contains in that file as following way:

LOADI      0
STORE      499
TRAP      0
STORE      498
LOAD      498
SUBI      0
BRP      2
BRA      14
LOAD      499
ADD       498
STORE       499
LOAD      498
SUBI      1
STORE      498
BRA      -22
LOAD      499
TRAP      1
STOP      0
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

CEHJCommented:
>>i have attached the example

Nope - all you attached was a small app concerned with RMARepair.

So you've just posted a good sample. What bad sample are you trying to protect against?
0
adam_progAuthor Commented:
bad example if the opcode is missing should print option 1- Invalid opcode
0
CEHJCommented:
Because you're using a Scanner and because of its default delimiters, that's relatively tricky - you'll only find a missing int code when you try to parse an instruction (since the number is missing) as an int.

I would be inclined to read lines and split into a 2-element array. You can then count the elements and take action if < 2 and !stop
0
adam_progAuthor Commented:
can you code it or what my code should be?
0
CEHJCommented:
Essentially just:
in.useDelimiter("[\r\n]");
...
 
String[] instAndOpCode = in.nextLine().split("\\s+");

Open in new window

0
adam_progAuthor Commented:
how the array could be done
0
CEHJCommented:
You'll find it even easier using this:

http://technojeeves.com/joomla/index.php/free/74-string-list

>>how the array could be done

Check the element count - it will tell you if the opcode is missing (or at least either instruction or opcode)
0
adam_progAuthor Commented:
I tried to put the array but it still only print one line... I only want to print or write the all content on the file... as anyone can help or can fix my code...i appreciate... thanks.. here is the code

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
class CSE340Project1
{
 
	public static void main(String args[])
	{
		ArrayList inputList= new ArrayList();
		String filename,line,fileToSave;
		Boolean check = false;
		Boolean cont = false;
		Scanner scan = new Scanner(System.in);
 
 
					
		System.out.println("Enter the file name");
		filename = scan.next();
		//filename BufferReader.next();
		filename = filename.toLowerCase();
 
		try
		{
			check = checkFilename(filename);
			cont = true;
		}
		catch(Exception e)
		{
			System.out.println("Assembily not complete - Illegal file name");
		}
		if(cont)
		{
			try
			{
				
				FileInputStream fstream = new FileInputStream(filename);
				BufferedReader readLine = new BufferedReader (new InputStreamReader(System.in));
				DataInputStream in = new DataInputStream(fstream);
				int count = 0;
				//line = in.readLine();
				//count++;
				while ( in.available() !=0)
				{
					line = in.readLine();
					//inputList.add(new Code(line));
						
					String line1[]= line.split("\\s+");
					count++;
				}
 
				in.close();
		        
			}
			
			catch (Exception e)
			
			{
				System.err.println("Assembily not complete - File does not exist");
				cont = false;
			}
			if(cont)
			{
				fileToSave = filename.replace(".src",".");
				cont = createListingFile(inputList,fileToSave);
				cont =	createExecutableFile(inputList,fileToSave);
			}
			if(cont)
			{
				System.out.println("Assembly complete. No errors");
			}
 
		}
	}
 
	public static Boolean createListingFile(ArrayList list, String fileToSave)
	{
		FileOutputStream out; 			// declare a file output object
		PrintStream p; 					// declare a print stream object
		int lineCount = 0;
		Boolean result = true;
 
		try
		{
			// Create a new file output stream
			out = new FileOutputStream(fileToSave + "lis");
 
			// Connect print stream to the output stream
			p = new PrintStream( out );
 
			//p.println ("This is written to a file");
			p.println("Loc\tOpCode\tOperand");
			for(int index = 0; index < list.size(); index++)
			{
				Code temp = (Code)list.get(index);
				lineCount++;
				//prints one line for current code object
				p.println(2*index+"\t"+temp.getOpcode()+"\t"+temp.getOperand()+"\t"+
				(index+1)+".\t"+temp.getOpcodeSource()+"\t"+temp.getOperand()+"\t"+
				temp.getComment());
				if(temp.getErrorStatus())
				{
					p.println("Error: "+temp.getErrorMessage());
					System.out.print("Error: "+temp.getErrorMessage()+"\nOccured at line number: "+lineCount+"\n");
					throw new Exception();
				}
			}
			p.close();
 
		}
		catch (Exception e)
		{
			System.err.println ("Assembily error");
			result = false;
		}
		return result;
	}
	public static Boolean createExecutableFile(ArrayList list, String fileToSave)
	{
 
		FileOutputStream out; // declare a file output object
		PrintStream p; // declare a print stream object
		int lineCount = 0;
		Boolean result = true;
 
		try
		{
			// Create a new file output stream
			out = new FileOutputStream(fileToSave + "xxx");
 
			// Connect print stream to the output stream
			p = new PrintStream( out );
 
			for(int index = 0; index < list.size(); index++)
			{
				Code temp = (Code)list.get(index);
				lineCount++;
				if(temp.getErrorStatus())
				{
					System.out.print("Error: "+temp.getErrorMessage()+"\nOccured at line number: "+lineCount+"\n");
					throw new Exception();
				}
				else
				{
					p.println(temp.getOpcode());
					p.println(temp.getOperand());
				}
			}
			//p.println ("This is written to a file");
			p.close();
 
		}
		catch (Exception e)
		{
			System.err.println ("Assembily error");
			result = false;
		}
		return result;
	}
	public static Boolean checkFilename(String filename) throws Exception
	{
		Boolean result = false;
		if(filename.endsWith(".src"))
			result = true;
		else
			throw new Exception();
		return result;
	}
}

Open in new window

0
CEHJCommented:
Replace

>>
        FileInputStream fstream = new FileInputStream(filename);
        BufferedReader readLine = new BufferedReader(new InputStreamReader(
                    System.in));
        DataInputStream in = new DataInputStream(fstream);
        int count = 0;

        //line = in.readLine();
        //count++;
        while (in.available() != 0) {
            line = in.readLine();

            //inputList.add(new Code(line));
            String[] line1 = line.split("\\s+");
            count++;
        }

        in.close();
>>

by
        BufferedReader readLine = new BufferedReader(new FileReader(filename));
        int count = 0;
        String line = null;
        while ((line = in.readLine()) != null) {
            String[] line1 = line.split("\\s+");
            count++;
            System.out.printf("Number of tokens on line %d is %d\n", count, line1.length);
        }
        in.close();

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
adam_progAuthor Commented:
very good
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.