Question

Need help with java programming. Here is what I need to do: Write a Java program...

Need help with java programming.

Here is what I need to do:

Write a Java program that could help test programs that use text files. Your program will copy an input file to standard output, but whenever it sees a “$integer”, will replace that variable by a corresponding value in a 2ndfile, which will be called the “variable value file”.

The requirements for the assignment:

1.     The input and variable value file are both text files that will be specified in the command line. The way to run your program will thus be:

java cs401hw1.GenTextFile input_file variable_value_file

2.     As indicated above, input_file is just a regular text file. Your code should not generate output based on the names of the files, of course.

3.     Similarly, variable_value_file is also a regular text file, but each line of the file is considered to be the value of the next variable. That is, the first line of the file is the value of $0, the 2nd line is the value of $1, the 3rd line is the value of $2, and so on. The value does not include the end-of-line.

a.      The java.util.Scanner class lets you easily read in the lines. Construct a File using the 2nd command-line argument, then pass this File to the constructor for Scanner

4.     When a variable ($integer) is encountered in the input file, the corresponding line from the variable values file is displayed instead.

a.      The java.io.FileReader class has a read() method that will read one character at a time

b.     To convert the characters for integer into an actual integer value the static method Integer.parseInt(String) is helpful

5.     A variable does not have to be used, or it may be used more than once.

6.     Variable numbers are in the range of 0 to 9999.

7.     Any two variables are separated by at least one character (so $1$2 won’t be in the input)

8.     Comment each function to explain what the function does, as well as the overall program.

9.     Choose good variable and function names

10.  Name the constants you use

Example:

$0 POPULATION GROWTH

(each * represents $1 person)

$2 $3

variable value file:

Town

1

1800

*

Expected output:

Town POPULATION GROWTH

(each * represents 1 person)

1800 *


PLEASE WRITE PROGRAM CLEARLY!!!!

0 0
Add a comment Improve this question Transcribed image text
Answer #1

JAVA PROGRAM

package cs401hw1;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

//Class: GenTextFile
public class GenTextFile {
  
   private String inputFile; //instance variable inputFile
   private String varValFile; //instance variable varValFile
  
   //Constructor
   //Take values from input arguments and populate instance variables
   public GenTextFile(String[] args){
       if(args!=null && args.length==2){
           inputFile = args[0];
           varValFile = args[1];
       }else{ //if invalid number of arguments
           System.out.println("Invalid arguments!");
       }
   }
   public static void main(String[] args){
      
       GenTextFile gtf = new GenTextFile(args); //Create GenTextFile instance
       String currentLine = null;
      
       Scanner inFileScanner = gtf.createFileScanner(gtf.inputFile); //Create input file Scanner instance
       List<String> variables = gtf.createVariables(gtf.varValFile); //Create List of variables from varValFile
      
       if(inFileScanner!=null){
       while(inFileScanner.hasNextLine()){ //As long as there is a line in input file
           currentLine = inFileScanner.nextLine(); //read the line
           String updatedLineData = gtf.generateFinalDataForALine(currentLine, variables); //generate updted line data by replacing variables
           System.out.println(updatedLineData);//print the updated line in console
       }
         
       inFileScanner.close();//close input file scanner
       }
      
      
   }
  
   /**
   * Generate final data for currentLine by replacing variable
   * @param currentLine
   * @param variables
   * @return
   */
   private String generateFinalDataForALine(String currentLine,List<String> variables){
       StringBuilder sb = new StringBuilder();//Create Stringbuilder
       char[] lineData = currentLine.toCharArray(); //Convert the currentLine String into CharArray
  
       for(int i = 0; i < lineData.length; i++){ //Traverse through individual characters
      
           //If current Character is '$'
           //Read next consecutive characters as long as they are digit
           if(lineData[i]=='$'){
           String indexStr = "";
           char currentChar;
           int p;
           for( p = i+1; p < lineData.length; p++){ //traverse from next characters
               currentChar = lineData[p];
               if(!Character.isDigit(currentChar)){ //if it is not a digit break
                   i = p-1;
                   break;
               }
               indexStr +=currentChar; //concat digits into indexStr
           }
           int index = Integer.parseInt(indexStr); //convert indexStr into int index
           String variable = variables.get(index); //get variable from variables list at the index
           sb.append(variable); //append that variable in string builder
           if(p==lineData.length){//if the current digit is the last character of the line, breaks from outer for loop
               break;
           }
       }else{
           //otherwise add the not digit character into the stringBuilder
           sb.append(lineData[i]);
       }
   }
  
   return sb.toString();//return string from the string builder
   }
  
  
   //Create file scanner from the given filename
   private Scanner createFileScanner(String fileName){
       Scanner file = null;
       try {
           file = new Scanner(new File(fileName));
       } catch (FileNotFoundException e) {
           System.out.println("Input file:"+fileName+" is not found!");
       }
      
       return file;
   }
  
   /**
   * Create list of variables from the variable file name
   * @param varFileName
   * @return
   */
   private List<String> createVariables(String varFileName){
       Scanner varFileScanner = createFileScanner(varFileName); //create file scanner
       List<String> variables = null;
      
       if(varFileScanner!=null){
           variables = new ArrayList<String>();
           while(varFileScanner.hasNextLine()){
               variables.add(varFileScanner.nextLine());//add every line of file into the list
           }
           varFileScanner.close();//close var file scanner
       }
      
       return variables;
      
   }
}

=====================================

THE FILES USED

=====================================

InputFile.txt

$0 POPULATION GROWTH
(each * represents $1 person)
$2 $3

VariableFile.txt

Town
1
1800
*

=========================================

OUTPUT

=========================================

First set the input arguments to the program from eclipse Run Configurations.

Run Configurations Create, manage, and run configurations Run a Java application J B X Name: GenTextFile Main (= Arguments JR

The output obtained after the program ran is below:

A Problems @ Javadoc Console X <terminated > GenTextFile [Java Application) C:\Program FilesVava\jre 1.8.0_121\bin\javaw.exe

Add a comment
Know the answer?
Add Answer to:
Need help with java programming. Here is what I need to do: Write a Java program...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • //I NEED THE PROGRAM IN C LANGUAGE!// QUESTION: I need you to write a program which...

    //I NEED THE PROGRAM IN C LANGUAGE!// QUESTION: I need you to write a program which manipulates text from an input file using the string library. Your program will accept command line arguments for the input and output file names as well as a list of blacklisted words. There are two major features in this programming: 1. Given an input file with text and a list of words, find and replace every use of these blacklisted words with the string...

  • java Program Write a program called Copy that accepts the names of an input file and...

    java Program Write a program called Copy that accepts the names of an input file and an output file on the command line and copies the contents of the input file to the output file, for example, csc$ java Copy infile.txt outfile.txt

  • 4.3Learning Objective: To read and write text files. Instructions: This is complete program with one Java...

    4.3Learning Objective: To read and write text files. Instructions: This is complete program with one Java source code file named H01_43.java (your main class is named H01_43). Problem: Write a program that prompts the user for the name of a Java source code file (you may assume the file contains Java source code and has a .java filename extension; we will not test your program on non-Java source code files). The program shall read the source code file and output...

  • Regular Expression processor in Java Overview: Create a Java program that will accept a regular expression...

    Regular Expression processor in Java Overview: Create a Java program that will accept a regular expression and a filename for a text file. The program will process the file, looking at every line to find matches for the regular expression and display them. Regular Expression Format The following operators are required to be accepted: + - one or more of the following character (no groups) * - zero or more of the following character (no groups) [] – no negation,...

  • java Write a program called Copy that accepts the names of an input file and an...

    java Write a program called Copy that accepts the names of an input file and an output file on the command line and copies the contents of the input file to the output file, for example, csc$ java Copy infile.txt outfile.txt

  • Write a Java program called Flying.java that, firstly, prompts (asks) the user to enter an input...

    Write a Java program called Flying.java that, firstly, prompts (asks) the user to enter an input file name. This is the name of a text file that can contain any number of records. A record in this file is a single line of text in the following format: Num of passengers^range^name^manufacturer^model where: Num of passengers is the total number of people in the plane. This represents an integer number, but remember that it is still part of the String so...

  • After reading pages 330 - 336, write a program that takes two command line arguments which...

    After reading pages 330 - 336, write a program that takes two command line arguments which are file names. The program should read the first file line by line and write each line, in reverse order, into the second file. The program should include a "usage" method that displays the correct command line syntax if two file names are not provided. Example: if my input file says Hello, World! then my output file will contain !dlroW ,olleH Hints: Use CaesarCipher...

  • FOR JAVA Write a program that takes two command line arguments: an input file and an...

    FOR JAVA Write a program that takes two command line arguments: an input file and an output file. The program should read the input file and replace the last letter of each word with a * character and write the result to the output file. The program should maintain the input file's line separators. The program should catch all possible checked exceptions and display an informative message. Notes: This program can be written in a single main method Remember that...

  • . . In this programming assignment, you need to write a CH+ program that serves as...

    . . In this programming assignment, you need to write a CH+ program that serves as a very basic word processor. The program should read lines from a file, perform some transformations, and generate formatted output on the screen. For this assignment, use the following definitions: A "word" is a sequence of non-whitespace characters. An "empty line" is a line with no characters in it at all. A "blank line" is a line containing only one or more whitespace characters....

  • I need help with a java program Write a program Enigma that takes a single String...

    I need help with a java program Write a program Enigma that takes a single String as a command line argument. Enigma should read the file specified by the String argument, add 5 to each byte, and leave the altered data values in a file whose name is the command line argument. Note that this "updating in place" is the most difficult part of this lab: java Enigma sophie.dat should read file sophie.dat, and upon completion, leave the modified data...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT