import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; /* Java application that uses an instance of the TuringMachine class ** to simulate computations of a Turing Machine. ** Author: R. McCloskey ** Date: May 2026 */ public class TM_App2 { /* Two or three command-line arguments are expected: ** args[0]: name of file containing list of TM transitions ** Each transition should be on a line by itself. ** Example: "3 a 1 b R" describes the transition from state 3 to state 1 ** on an 'a', which is replaced by 'b' and the read-write head moves ** one place to the Right. (Use 'L' for left.) ** args[1]: ID of the initial state (an integer) ** args[2]: name of file containing input strings to be tested. */ public static void main(String[] args) throws FileNotFoundException { // Create a Turing Machine whose transitions are those found in // the file whose name is the first command line argument. String fileName = args[0]; Scanner in = new Scanner(new File(fileName)); TuringMachine tm = new TuringMachine(in); // Establish the initial state and the input string, which are // specified by the 2nd and 3rd command line arguments. int initState = Integer.parseInt(args[1]); boolean echo; if (args.length < 3) { in = new Scanner(System.in); echo = false; } else { in = new Scanner(new File(args[2])); echo = true; } boolean keepGoing = true; while (keepGoing) { System.out.print("\nEnter input string:"); String inputString = in.nextLine().trim(); if (inputString.length() == 0) { keepGoing = false; } else { if (echo) { System.out.println(inputString); } System.out.print("Enter max # of steps to simulate:"); int maxSteps = in.nextInt(); in.nextLine(); if (echo) { System.out.println(maxSteps); } int stepsSimulated = runTM(tm, initState, inputString, maxSteps); System.out.println("# of steps simulated: " + stepsSimulated); if (!tm.hasHalted()) { System.out.println("NOTE: Simulation aborted before halting"); } System.out.println("Input was " + inputString); } } System.out.println("\nGoodbye."); } /* Simulates the given Turing machine (starting in the specified state) ** on the given input string for no more than the number of steps ** indicated by the given "time limit". Returns the number of steps ** that were simulated. */ public static int runTM(TuringMachine tm, int initState, String inputString, int timeLimit) { // Establish the Turing Machine's initial instantaneous description // and display it. tm.start(initState, inputString); System.out.println(tm.imageOfID()); // Run the Turing Machine until it halts or until the time limit has // been reached, displaying the computation's instantaneous description // after every move. int numSteps = 0; while (!tm.hasHalted() && numSteps != timeLimit) { tm.move(); System.out.println(tm.imageOfID()); numSteps++; } return numSteps; } }