Sunteți pe pagina 1din 40

System Programming | File

Experiment 1
Aim: Write a program of Binary Search
Code:
import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");

for (c = 0; c < n; c++)


array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + " found at location " + (middle + 1) + ".");
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
System.out.println(search + " is not present in the list.\n");
}
}

13113027

System Programming | File

Output:

13113027

System Programming | File

Experiment 2
Aim: Write a program of Linear Search
Code:

import java.util.Scanner;
class LinearSearch
{
public static void main(String args[])
{
int c, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
for (c = 0; c < n; c++)
{
if (array[c] == search) /* Searching element is present */
{
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
}
if (c == n) /* Searching element is absent */
System.out.println(search + " is not present in array.");
}
}

13113027

System Programming | File

Output:

13113027

System Programming | File

Experiment 3
Aim: Write a program of Quick Sort
Code:
import java.util.Scanner;

public class QuickSort


{
public static void sort(int[] arr)
{
quickSort(arr, 0, arr.length - 1);
}
public static void quickSort(int arr[], int low, int high)
{
int i = low, j = high;
int temp;
int pivot = arr[(low + high) / 2];

while (i <= j)
{
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;

i++;
j--;
}
}

13113027

System Programming | File


if (low < j)
quickSort(arr, low, j);
if (i < high)
quickSort(arr, i, high);
}
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
System.out.println("Quick Sort Test\n");
int n, i;
System.out.println("Enter number of integer elements");
n = scan.nextInt();
int arr[] = new int[ n ];
System.out.println("\nEnter "+ n +" integer elements");
for (i = 0; i < n; i++)
arr[i] = scan.nextInt();
sort(arr);
System.out.println("\nElements after sorting ");
for (i = 0; i < n; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}

13113027

System Programming | File

Output:

13113027

System Programming | File

Experiment 4
Aim: Write a program of Heap Sort
Code:
public class HeapSort
{
public void sort(int arr[])
{
int n = arr.length;

for (int i = n / 2 - 1; i >= 0; i--)


heapify(arr, n, i);

for (int i=n-1; i>=0; i--)


{
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;

heapify(arr, i, 0);
}
}

void heapify(int arr[], int n, int i)


{
int largest = i;
int l = 2*i + 1;
int r = 2*i + 2;

if (l < n && arr[l] > arr[largest])


largest = l;

if (r < n && arr[r] > arr[largest])


largest = r;

13113027

System Programming | File

if (largest != i)
{
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
heapify(arr, n, largest);
}
}
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}

public static void main(String args[])


{
Scanner scan = new Scanner( System.in );
int n, i;
System.out.println("Enter number of integer elements");
n = scan.nextInt();
int arr[] = new int[ n ];
System.out.println("\nEnter "+ n +" integer elements");
for (i = 0; i < n; i++)
arr[i] = scan.nextInt();

HeapSort ob = new HeapSort();


ob.sort(arr);
System.out.println("Sorted array is");
printArray(arr);
}
}

13113027

System Programming | File

Output:

10

13113027

System Programming | File

Experiment 5
Aim: Write a program of Merge Sort
Code:
import java.util.Scanner;
public class MergeSort
{
public static void sort(int[] a, int low, int high)
{
int N = high - low;
if (N <= 1)
return;
int mid = low + N/2;
sort(a, low, mid);
sort(a, mid, high);
int[] temp = new int[N];
int i = low, j = mid;
for (int k = 0; k < N; k++)
{
if (i == mid)
temp[k] = a[j++];
else if (j == high)
temp[k] = a[i++];
else if (a[j]<a[i])
temp[k] = a[j++];
else
temp[k] = a[i++];
}
for (int k = 0; k < N; k++)
a[low + k] = temp[k];
}
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
System.out.println("Merge Sort Test\n");
int n, i;
System.out.println("Enter number of integer elements");
n = scan.nextInt();
int arr[] = new int[ n ];
System.out.println("\nEnter "+ n +" integer elements");
for (i = 0; i < n; i++)
arr[i] = scan.nextInt();
sort(arr, 0, n);
System.out.println("\nElements after sorting ");
for (i = 0; i < n; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}

11

13113027

System Programming | File

Output:

12

13113027

System Programming | File

Experiment 6
Aim: Write a program of Text Editor
Code:
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.io.*;
import java.awt.event.*;
import java.util.Hashtable;
public class SimpleEditor extends JFrame {
private Action openAction = new OpenAction();
private Action saveAction = new SaveAction();
private JTextComponent textComp;
private Hashtable actionHash = new Hashtable();
public static void main(String[] args) {
SimpleEditor editor = new SimpleEditor();
editor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
editor.setVisible(true);
}
public SimpleEditor() {
super("Swing Editor");
textComp = createTextComponent();
makeActionsPretty();
Container content = getContentPane();
content.add(textComp, BorderLayout.CENTER);
content.add(createToolBar(), BorderLayout.NORTH);
setJMenuBar(createMenuBar());
setSize(320, 240);
}
protected JTextComponent createTextComponent() {
JTextArea ta = new JTextArea();
ta.setLineWrap(true);
return ta;
}
protected void makeActionsPretty() {
Action a;
a = textComp.getActionMap().get(DefaultEditorKit.cutAction);
a.putValue(Action.SMALL_ICON, new ImageIcon("icons/cut.gif"));
a.putValue(Action.NAME, "Cut");
a = textComp.getActionMap().get(DefaultEditorKit.copyAction);
a.putValue(Action.SMALL_ICON, new ImageIcon("icons/copy.gif"));
a.putValue(Action.NAME, "Copy");
a = textComp.getActionMap().get(DefaultEditorKit.pasteAction);
a.putValue(Action.SMALL_ICON, new ImageIcon("icons/paste.gif"));
a.putValue(Action.NAME, "Paste");
a = textComp.getActionMap().get(DefaultEditorKit.selectAllAction);

13

13113027

System Programming | File


a.putValue(Action.NAME, "Select All");
}
protected JToolBar createToolBar() {
JToolBar bar = new JToolBar();
bar.add(getOpenAction()).setText("");
bar.add(getSaveAction()).setText("");
bar.addSeparator();
bar.add(textComp.getActionMap().get(DefaultEditorKit.cutAction)).setText("");
bar.add(textComp.getActionMap().get(
DefaultEditorKit.copyAction)).setText("");
bar.add(textComp.getActionMap().get(
DefaultEditorKit.pasteAction)).setText("");
return bar;
}
protected JMenuBar createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu edit = new JMenu("Edit");
menubar.add(file);
menubar.add(edit);
file.add(getOpenAction());
file.add(getSaveAction());
file.add(new ExitAction());
edit.add(textComp.getActionMap().get(DefaultEditorKit.cutAction));
edit.add(textComp.getActionMap().get(DefaultEditorKit.copyAction));
edit.add(textComp.getActionMap().get(DefaultEditorKit.pasteAction));
edit.add(textComp.getActionMap().get(DefaultEditorKit.selectAllAction));
return menubar;
}
protected Action getOpenAction() { return openAction; }
protected Action getSaveAction() { return saveAction; }
protected JTextComponent getTextComponent() { return textComp; }
public class ExitAction extends AbstractAction {
public ExitAction() { super("Exit"); }
public void actionPerformed(ActionEvent ev) { System.exit(0); }
}
class OpenAction extends AbstractAction {
public OpenAction() {
super("Open", new ImageIcon("icons/open.gif"));
}

public void actionPerformed(ActionEvent ev) {


JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(SimpleEditor.this) !=
JFileChooser.APPROVE_OPTION)
return;
File file = chooser.getSelectedFile();
if (file == null)
return;

14

13113027

System Programming | File

FileReader reader = null;


try {
reader = new FileReader(file);
textComp.read(reader, null);
}
catch (IOException ex) {
JOptionPane.showMessageDialog(SimpleEditor.this,
"File Not Found", "ERROR", JOptionPane.ERROR_MESSAGE);
}
finally {
if (reader != null) {
try {
reader.close();
} catch (IOException x) {}
}
}
}
}
class SaveAction extends AbstractAction {
public SaveAction() {
super("Save", new ImageIcon("icons/save.gif"));
}

public void actionPerformed(ActionEvent ev) {


JFileChooser chooser = new JFileChooser();
if (chooser.showSaveDialog(SimpleEditor.this) !=
JFileChooser.APPROVE_OPTION)
return;
File file = chooser.getSelectedFile();
if (file == null)
return;
FileWriter writer = null;
try {
writer = new FileWriter(file);
textComp.write(writer);
}
catch (IOException ex) {
JOptionPane.showMessageDialog(SimpleEditor.this,
"File Not Saved", "ERROR", JOptionPane.ERROR_MESSAGE);
}
finally {
if (writer != null) {
try {
writer.close();
} catch (IOException x) {}
}
}
}
}
}

15

13113027

System Programming | File

Output:

16

13113027

System Programming | File

17

13113027

System Programming | File

Experiment 7
Aim: Write a program of Syntax Checker
Code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;

import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class JavaSyntaxChecker {


public static void main(String[] args) {
System.out.println(JavaSyntaxChecker.check("/home/pp/Desktop/Buggy.java"));
}

public static List<String> check(String file) {


JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);


Iterable<? extends JavaFileObject> compilationUnits =
fileManager.getJavaFileObjectsFromStrings(Arrays.asList(file));

DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();


compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits).call();

List<String> messages = new ArrayList<String>();


Formatter formatter = new Formatter();
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {

18

13113027

System Programming | File


messages.add(diagnostic.getKind() + ":\t Line [" + diagnostic.getLineNumber() + "] \t Position [" +
diagnostic.getPosition() + "]\t" + diagnostic.getMessage(Locale.ROOT) + "\n");
}

return messages;
}
}

File to Check
public class HelloBuggyWorld {
String test // missing a semicolon

public static void main (String [] args) {


System.out.println('Hello World!'); // should be double quoted
}
}

Output:

19

13113027

System Programming | File

Experiment 8
Aim: Write a program of Scheduling algorithm
Code:
import java.io. * ;
class fcfs {
public static void main(String args[]) throws Exception {
int n,
AT[],
BT[],
WT[],
TAT[];
float AWT = 0;
InputStreamReader isr = new InputStreamReader(System. in );
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter no of process");
n = Integer.parseInt(br.readLine());
BT = new int[n];
WT = new int[n];
TAT = new int[n];
AT = new int[n];
System.out.println("Enter Burst time for each process\n");
for (int i = 0; i < n; i++) {
System.out.println("Enter BT for process " + (i + 1));
BT[i] = Integer.parseInt(br.readLine());
}
for (int i = 0; i < n; i++) {
System.out.println("Enter AT for process" + i);
AT[i] = Integer.parseInt(br.readLine());
}
WT[0] = 0;
for (int i = 1; i < n; i++) {
WT[i] = WT[i - 1] + BT[i - 1];
WT[i] = WT[i] - AT[i];
}
for (int i = 0; i < n; i++) {
TAT[i] = WT[i] + BT[i];
AWT = AWT + WT[i];
}
System.out.println(" PROCESS BT WT TAT ");
for (int i = 0; i < n; i++) {
System.out.println(" " + i + " " + BT[i] + " " + WT[i] +
" " + TAT[i]);
}
AWT = AWT / n;
System.out.println("Avg waiting time=" + AWT + "\n");
}
}

20

13113027

System Programming | File

Output:

21

13113027

System Programming | File

Experiment 9
Aim: Write a program of Round Robin
Code:
import java.io.*;
import java.util.*;
class Round {
public static void main(String args[]) throws IOException {
Scanner scan=new Scanner(System.in);
int i,
j,
k,
q,
sum = 0;
System.out.println("Enter number of process:");
int n = scan.nextInt();
int bt[] = new int[n];
int wt[] = new int[n];
int tat[] = new int[n];
int a[] = new int[n];
System.out.println("Enter brust Time:");
for (i = 0; i < n; i++) {
System.out.println("Enter brust Time for " + (i + 1));
bt[i] = scan.nextInt();
}
System.out.println("Enter Time quantum:");
q = scan.nextInt();
for (i = 0; i < n; i++)
a[i] = bt[i];
for (i = 0; i < n; i++) {
wt[i] = 0;
}
do {
for (i = 0; i < n; i++) {
if (bt[i] > q) {
bt[i] -= q;
for (j = 0; j < n; j++) {
if ((j != i) && (bt[j] != 0)) wt[j] += q;
}
} else {
for (j = 0; j < n; j++) {
if ((j != i) && (bt[j] != 0)) wt[j] += bt[i];
}
bt[i] = 0;
}
}
sum = 0;
for (k = 0; k < n; k++)
sum = sum + bt[k];
}
while ( sum != 0 );
for (i = 0; i < n; i++) {
tat[i] = wt[i] + a[i];

22

13113027

System Programming | File


}
System.out.println("process\t\tBT\tWT\tTAT");
for (i = 0; i < n; i++) {
System.out.println("process" + (i + 1) + "\t" + a[i] + "\t" + wt[i] + "\t" + tat[i]);
}
float avg_wt = 0;
float avg_tat = 0;
for (j = 0; j < n; j++) {
avg_wt += wt[j];
}
for (j = 0; j < n; j++) {
avg_tat += tat[j];
}
System.out.println("average waiting time " + (avg_wt / n) + "\n Average turn around time" +
(avg_tat / n));
}
}

Output:

23

13113027

System Programming | File

24

13113027

System Programming | File

Experiment 10
Aim: Write a program of STG
Code:
import java.util. * ;
class STG {
public static void main(String args[]) {
Scanner sc = new Scanner(System. in );
int n,
BT[],
WT[],
TAT[];
System.out.println("Enter no of process");
n = sc.nextInt();
BT = new int[n + 1];
WT = new int[n + 1];
TAT = new int[n + 1];
float AWT = 0;
System.out.println("Enter Burst time for each process");
for (int i = 0; i < n; i++) {
System.out.println("Enter BT for process " + (i + 1));
BT[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
WT[i] = 0;
TAT[i] = 0;
}
int temp;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
if (BT[j] > BT[j + 1]) {
temp = BT[j];
BT[j] = BT[j + 1];
BT[j + 1] = temp;
temp = WT[j];
WT[j] = WT[j + 1];
WT[j + 1] = temp;
}
}
}
for (int i = 0; i < n; i++) {
TAT[i] = BT[i] + WT[i];
WT[i + 1] = TAT[i];
}
TAT[n] = WT[n] + BT[n];
System.out.println(" PROCESS BT WT TAT ");
for (int i = 0; i < n; i++)
System.out.println(" " + i + " " + BT[i] + " " + WT[i] + " " + TAT[i]);
for (int j = 0; j < n; j++)
AWT += WT[j];

25

13113027

System Programming | File


AWT = AWT / n;
System.out.println("Avg waiting time=" + AWT + "\n");
}
}

Output:

26

13113027

System Programming | File

Experiment 11
Aim: Write a program of 2 pass assembler
Code:

import java.util.*;
import java.io.*;

class Tuple {
String mnemonic, bin_opcode, type;
int length;

Tuple() {}

Tuple(String s1, String s2, String s3, String s4) {


mnemonic = s1;
bin_opcode = s2;
length = Integer.parseInt(s3);
type = s4;
}
}

class SymTuple {
String symbol, ra;
int value, length;

SymTuple(String s1, int i1, int i2, String s2) {


symbol = s1;
value = i1;
length = i2;
ra = s2;
}
}

class LitTuple {

27

13113027

System Programming | File


String literal, ra;
int value, length;

LitTuple() {}

LitTuple(String s1, int i1, int i2, String s2) {


literal = s1;
value = i1;
length = i2;
ra = s2;
}
}

class TwoPassAssembler {
static int lc;
static List<Tuple> mot;
static List<String> pot;
static List<SymTuple> symtable;
static List<LitTuple> littable;
static List<Integer> lclist;
static Map<Integer, Integer> basetable;
static PrintWriter out_pass2;
static PrintWriter out_pass1;
static int line_no;

public static void main(String args[]) throws Exception {


initializeTables();
System.out.println("====== PASS 1 ======\n");
pass1();
System.out.println("\n====== PASS 2 ======\n");
pass2();
}

static void pass1() throws Exception {

28

13113027

System Programming | File


BufferedReader input = new BufferedReader(new InputStreamReader(new
FileInputStream("input.txt")));
out_pass1 = new PrintWriter(new FileWriter("output_pass1.txt"), true);
PrintWriter out_symtable = new PrintWriter(new FileWriter("out_symtable.txt"), true);
PrintWriter out_littable = new PrintWriter(new FileWriter("out_littable.txt"), true);
String s;
while((s = input.readLine()) != null) {
StringTokenizer st = new StringTokenizer(s, " ", false);
String s_arr[] = new String[st.countTokens()];
for(int i=0 ; i < s_arr.length ; i++) {
s_arr[i] = st.nextToken();
}
if(searchPot1(s_arr) == false) {
searchMot1(s_arr);
out_pass1.println(s);
}
lclist.add(lc);
}
int j;
String output = new String();
System.out.println("Symbol Table:");
System.out.println("Symbol

Value Length R/A");

for(SymTuple i : symtable) {
output = i.symbol;
for(j=i.symbol.length() ; j < 10 ; j++) {
output += " ";
}
output += i.value;
for(j=new Integer(i.value).toString().length() ; j < 7 ; j++) {
output += " ";
}
output += i.length + "

" + i.ra;

System.out.println(output);
out_symtable.println(output);
}

29

13113027

System Programming | File


System.out.println("\nLiteral Table:");
System.out.println("Literal Value Length R/A");
for(LitTuple i : littable) {
output = i.literal;
for(j=i.literal.length() ; j < 10 ; j++) {
output += " ";
}
output += i.value;
for(j=new Integer(i.value).toString().length() ; j < 7 ; j++) {
output += " ";
}
output += i.length + "

" + i.ra;

System.out.println(output);
out_littable.println(output);
}
}

static void pass2() throws Exception {


line_no = 0;
out_pass2 = new PrintWriter(new FileWriter("output_pass2.txt"), true);
BufferedReader input = new BufferedReader(new InputStreamReader(new
FileInputStream("output_pass1.txt")));
String s;
System.out.println("Pass 2 input:");
while((s = input.readLine()) != null) {
System.out.println(s);
StringTokenizer st = new StringTokenizer(s, " ", false);
String s_arr[] = new String[st.countTokens()];
for(int i=0 ; i < s_arr.length ; i++) {
s_arr[i] = st.nextToken();
}
if(searchPot2(s_arr) == false) {
searchMot2(s_arr);
}
line_no++;

30

13113027

System Programming | File


}
System.out.println("\nPass 2 output:");
input = new BufferedReader(new InputStreamReader(new
FileInputStream("output_pass2.txt")));
while((s = input.readLine()) != null) {
System.out.println(s);
}
}

static boolean searchPot1(String[] s) {


int i = 0;
int l = 0;
int potval = 0;

if(s.length == 3) {
i = 1;
}
s = tokenizeOperands(s);

if(s[i].equalsIgnoreCase("DS") || s[i].equalsIgnoreCase("DC")) {
potval = 1;
}
if(s[i].equalsIgnoreCase("EQU")) {
potval = 2;
}
if(s[i].equalsIgnoreCase("START")) {
potval = 3;
}
if(s[i].equalsIgnoreCase("LTORG")) {
potval = 4;
}
if(s[i].equalsIgnoreCase("END")) {
potval = 5;
}

31

13113027

System Programming | File


switch(potval) {
case 1:
// DS or DC statement
String x = s[i+1];
int index = x.indexOf("F");
if(i == 1) {
symtable.add(new SymTuple(s[0], lc, 4, "R"));
}
if(index != 0) {
// Ends with F
l = Integer.parseInt(x.substring(0, x.length()-1));
l *= 4;
} else {
// Starts with F
for(int j=i+1 ; j<s.length ; j++) {
l += 4;
}
}
lc += l;
return true;

case 2:
// EQU statement
if(!s[2].equals("*")) {
symtable.add(new SymTuple(s[0], Integer.parseInt(s[2]), 1, "A"));
} else {
symtable.add(new SymTuple(s[0], lc, 1, "R"));
}
return true;

case 3:
// START statement
symtable.add(new SymTuple(s[0], Integer.parseInt(s[2]), 1, "R"));
return true;

32

13113027

System Programming | File

case 4:
// LTORG statement
ltorg(false);
return true;

case 5:
// END statement
ltorg(true);
return true;
}
return false;
}

static void searchMot1(String[] s) {


Tuple t = new Tuple();
int i = 0;
if(s.length == 3) {
i = 1;
}
s = tokenizeOperands(s);
for(int j=i+1 ; j < s.length ; j++) {
if(s[j].startsWith("=")) {
littable.add(new LitTuple(s[j].substring(1, s[j].length()), -1, 4, "R"));
}
}
if((i == 1) && (!s[0].equalsIgnoreCase("END"))) {
symtable.add(new SymTuple(s[0], lc, 4, "R"));
}
for(Tuple x : mot) {
if(s[i].equals(x.mnemonic)) {
t = x;
break;
}

33

13113027

System Programming | File


}
lc += t.length;
}

static void ltorg(boolean isEnd) {


Iterator<LitTuple> itr = littable.iterator();
LitTuple lt = new LitTuple();
boolean isBroken = false;
while(itr.hasNext()) {
lt = itr.next();
if(lt.value == -1) {
isBroken = true;
break;
}
}
if(!isBroken) {
return;
}
if(!isEnd) {
while(lc%8 != 0) {
lc++;
}
}
lt.value = lc;
lc += 4;
while(itr.hasNext()) {
lt = itr.next();
lt.value = lc;
lc += 4;
}
}

static boolean searchPot2(String[] s) {


int i = 0;

34

13113027

System Programming | File

if(s.length == 3) {
i = 1;
}
if(Collections.binarySearch(pot, s[i]) >= 0) {
if(s[i].equalsIgnoreCase("USING")) {
s = tokenizeOperands(s);

if(s[i+1].equals("*")) {
s[i+1] = lclist.get(line_no) + "";
} else {
for(int j=i+1 ; j<s.length ; j++) {
int value = getSymbolValue(s[j]);
if(value != -1) {
s[j] = value + "";
}
}
}
basetable.put(new Integer(s[i+2].trim()), new Integer(s[i+1].trim()));
}
return true;
}
return false;
}

static void searchMot2(String[] s) {


Tuple t = new Tuple();
int i = 0;
int j;

if(s.length == 3) {
i = 1;
}
s = tokenizeOperands(s);

35

13113027

System Programming | File

for(Tuple x : mot) {
if(s[i].equals(x.mnemonic)) {
t = x;
break;
}
}

String output = new String();


String mask = new String();
if(s[i].equals("BNE")) {
mask = "7";
} else if(s[i].equals("BR")) {
mask = "15";
} else {
mask = "0";
}
if(s[i].startsWith("B")) {
if(s[i].endsWith("R")) {
s[i] = "BCR";
} else {
s[i] = "BC";
}
List<String> temp = new ArrayList<>();
for(String x : s) {
temp.add(x);
}
temp.add(i+1, mask);
s = temp.toArray(new String[0]);
}
if(t.type.equals("RR")) {
output = s[i];
for(j=s[i].length() ; j<6 ; j++) {
output += " ";

36

13113027

System Programming | File


}
for(j=i+1 ; j<s.length ; j++) {
int value = getSymbolValue(s[j]);
if(value != -1) {
s[j] = value + "";
}
}
output += s[i+1];
for(j=i+2 ; j<s.length ; j++) {
output += ", " + s[j];
}
} else {
output = s[i];
for(j=s[i].length() ; j<6 ; j++) {
output += " ";
}
for(j=i+1 ; j<s.length-1 ; j++) {
int value = getSymbolValue(s[j]);
if(value != -1) {
s[j] = value + "";
}
}
s[j] = createOffset(s[j]);
output += s[i+1];
for(j=i+2 ; j<s.length ; j++) {
output += ", " + s[j];
}
}
out_pass2.println(output);
}

static String createOffset(String s) {


String original = s;
Integer[] key = basetable.keySet().toArray(new Integer[0]);

37

13113027

System Programming | File


int offset, new_offset;
int index = 0;
int value = -1;
int index_reg = 0;
if(s.startsWith("=")) {
value = getLiteralValue(s);
} else {
int paranthesis = s.indexOf("(");
String index_string = new String();
if(paranthesis != -1) {
s = s.substring(0, s.indexOf("("));
index_string = original.substring(original.indexOf("(")+1,
original.indexOf(")"));
index_reg = getSymbolValue(index_string);
}
value = getSymbolValue(s);
}
offset = Math.abs(value - basetable.get(key[index]));
for(int i=1 ; i<key.length ; i++) {
new_offset = Math.abs(value - basetable.get(key[i]));
if(new_offset < offset) {
offset = new_offset;
index = i;
}
}
String result = offset + "(" + index_reg + ", " + key[index] + ")";
return result;
}

static int getSymbolValue(String s) {


for(SymTuple st : symtable) {
if(s.equalsIgnoreCase(st.symbol)) {
return st.value;
}
}

38

13113027

System Programming | File


return -1;
}

static int getLiteralValue(String s) {


s = s.substring(1, s.length());
for(LitTuple lt : littable) {
if(s.equalsIgnoreCase(lt.literal)) {
return lt.value;
}
}
return -1;
}

static String[] tokenizeOperands(String[] s) {


List<String> temp = new LinkedList<>();
for(int j=0 ; j<s.length-1 ; j++) {
temp.add(s[j]);
}
StringTokenizer st = new StringTokenizer(s[s.length-1], " ,", false);
while(st.hasMoreTokens()) {
temp.add(st.nextToken());
}
s = temp.toArray(new String[0]);
return s;
}

static void initializeTables() throws Exception {


symtable = new LinkedList<>();
littable = new LinkedList<>();
lclist = new ArrayList<>();
basetable = new HashMap<>();
mot = new LinkedList<>();
pot = new LinkedList<>();
String s;

39

13113027

System Programming | File


BufferedReader br;
br = new BufferedReader(new InputStreamReader(new FileInputStream("mot.txt")));
while((s = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(s, " ", false);
mot.add(new Tuple(st.nextToken(), st.nextToken(), st.nextToken(), st.nextToken()));
}
br = new BufferedReader(new InputStreamReader(new FileInputStream("pot.txt")));
while((s = br.readLine()) != null) {
pot.add(s);
}
Collections.sort(pot);
}
}

40

13113027

S-ar putea să vă placă și