1. Write the program in java to replace the value of macro template with the macro expansion in the following lines of code.
Source code:
package assignment1;
import java.io.File;
import java.io.PrintStream;
import java.util.Scanner;
/**
*
* @author student
*/
public class Main2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args)throws Exception {
// TODO code application logic here
String macro = "";
String macroValue = "";
Scanner fin=new Scanner(new File("test.txt"));
while(fin.hasNext())
{
String str = fin.nextLine();
String str1 [] = str.split(" ");
//System.out.println(fin.nextLine());
if(str1[0].equals("#define"))
{
macro = str1[1];
macroValue = str1[2];
}
}
fin.close();
System.out.println("macro = "+macro);//printf("%s",macro);
System.out.println("macro value = "+macroValue);
Scanner fread=new Scanner(new File("test.txt"));
PrintStream fwrite=new PrintStream(new File("test3.txt"));
int i,j;
while(fread.hasNext())
{
String str = fread.nextLine();
int len = macro.length();
for(i=0; i < str.length(); i++)
{
if(str.charAt(i) == '"' )
{
do{
fwrite.print(str.charAt(i));
i++;
}while((str.charAt(i)!='"'));
fwrite.print(str.charAt(i));
}
else if (str.charAt(i) == macro.charAt(0) && str.charAt(0) != '#')
{
if(Character.isLetterOrDigit(str.charAt(i+macro.length())) || Character.isLetterOrDigit(str.charAt(i-1)))
fwrite.print(macro);
else
{
String temp = "";
for(j=i; j<i+len; j++)
{
temp = temp + str.charAt(j);
}
//System.out.println("temp ="+temp);
if(temp.equals(macro))
{
fwrite.print(macroValue);
// if(str.charAt(i+temp.length()))
}
}
i = i + len-1;
}
else
{
fwrite.print(str.charAt(i));
}
}
fwrite.println();
}
}
}
Output:
Nice work on the content coding, is it of BSCIT
ReplyDelete