Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Java | How do I get my program to save the printed output to a new file? Sample Input in my BWText.txt file: 10 REM
Java | How do I get my program to save the printed output to a new file?
Sample Input in my BWText.txt file:
10 REM compute the sum of integers with FOR loop: executes one time 20 TEXT : HOME : PR#0 30 FOR N=1 TO 0 STEP 1 40 LET S = S + N 50 PRINT N,S 70 NEXT N 80 PRINT : REM print empty line 90 PRINT "Final sum:";S 100 END
My program:
public class MyBasic { public static void main(String[] args) throws FileNotFoundException { //Load file Scanner scan = new Scanner(new File("C:\\Users\\leona\\OneDrive\\Desktop\\BWTest.txt")); String line = ""; String store[]; //Reading the file while(scan.hasNext()){ String eachLine = scan.nextLine(); //read each line from the file int indexOfFirstSpace = eachLine.indexOf(" "); //get the index of first space in the line eachLine = eachLine.substring(indexOfFirstSpace); // and extract the rest of string from that space //so that the first number added at the beginning of each line gets omitted when reading the file line = line + eachLine; } int flag = 1; store = line.split(" ");// Separate the tokens using the split function & save them in store array int len = store.length; int no1 = 1; String s[] = new String[100]; s[0] = "%"; int n = 0; System.out.println(" "); for (int i = 0; i < len; i++) { switch (store[i]) { // Switch loop identifies the different tokens case "REM": System.out.println(""); break; case "TEXT": System.out.println(" "); break; case "FOR": System.out.println(" "); break; case "STEP": System.out.println(" "); break; case "LET": System.out.println(" "); break; case "PRINT": System.out.println(" "); break; case "NEXT": System.out.println(" "); break; case "END": System.out.println(" "); break; case "-": System.out.println(" "); break; case "/": System.out.println(" "); break; case "%": System.out.println(" "); break; case "*": System.out.println(" "); break; case "=": System.out.println(" "); break; default: String b = store[i]; char ch[] = b.toCharArray(); //check if this Character array has something or not, check if its length is more than 0, then operate on it if(ch.length>0){ if (Character.isDigit(ch[0])) { System.out.println(" "); } else { if (Character.isLetter(ch[0])) { flag = 1; for (int j = 0; j < no1; j++) { if (s[j].equals(store[i])) { n = j; flag = 0; } } if (flag != 0) { s[no1] = store[i]; n = no1; no1++; } } } } } } System.out.println(" "); System.out.println("No of tokens: " + store.length); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started