简体   繁体   中英

Can not figure out how to create this program

Design a program that will read in the name of a file. From this file the program will read in a list of strings separated by blanks. These strings will be converted into their decimal equivalent and averaged. The program will then output the result to another file.

The program should also be able to gracefully handle input errors such as a bad file name or string data that does not contain a decimal value.

Cannot seem to figure out how to do 'the program will read in a list of strings separated by blanks. These strings will be converted into their decimal equivalent and averaged. The program will then output the result to another file.'

and

'The program should also be able to gracefully handle input errors such as a bad file name or string data that does not contain a decimal value.'

if anyone can explain or direct me on where to find examples of these I'd very much appreciate it.

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

    //Create a Scanner object
    Scanner input = new Scanner (System.in);

    //prompt the user to enter a file name
    System.out.println("Enter a file name: ");
    File file = new File (input.nextLine());  

    // Read text from file and change oldString to newString 
    try ( 
        // Create input file 
        Scanner input = new Scanner(file); 
    ) { 
        while (input.hasNext()) { 
            String s1 = input.nextLine(); 
            list.add(s1.replaceAll(args[1], args[2])); 
        } 
    } 


    // Save the change into the original file 
    try ( 
        // Create output file 
        PrintWriter output = new PrintWriter(file); 
    ) { 
        for (int i = 0; i < list.size(); i++) { 
            output.println(list.get(i)); 
       } 
    } 
}

The examples you seek are all over StackOverflow. You just need to choose a particular issue and research it.

When creating a Console application you should attempt to make it as User friendly as possible since the Console is rather limited with regards to just about everything. When prompting for input from the User, allow the User more than a single attempt should an entry error occur. A while loop is generally used for this sort of thing, here is an example:

//Create a Scanner object
Scanner input = new Scanner(System.in);

System.out.println("This application will read the file name you supply and");
System.out.println("average the scores on each file line. It will then write");
System.out.println("the results to another file you also supply the name for:");
System.out.println("Hit the ENTER Key to continue (or q to quit)....");
String in = "";
while (in.equals("")) {
    in = input.nextLine();
    if (in.equalsIgnoreCase("q")) {
        System.out.println("Bye-Bye");
        System.exit(0);
    }
    break;
}

// Prompt the user to enter a file name
String fileName = "";
File file = null;
while (fileName.equals("")) {
    System.out.println("Enter a file name (q to quit): ");
    fileName = input.nextLine();
    if (fileName.equalsIgnoreCase("q")) {
        System.out.println("Bye-Bye");
        System.exit(0);  // Quit Application
    }
    // If just ENTER key was hit 
    if (fileName.equals(""))  {
        System.out.println("Invalid File Name Provided! Try Again.");
        continue;
    }
    file = new File(fileName);
    // Does the supplied file exist? 
    if (!file.exists()) {
        // Nope!
        System.out.println("Invalid File Name Provided! Can Not Locate File! Try Again.");
        fileName = ""; // Make fileName hold Null String ("") to continue loop
    }
}

As for asking the User for a File Name, the above code is a more friendly approach. First it basically explains what the application does, it then allows the User to quit the application if he/she wishes and it allows the User to provide a correct entry should a faulty entry be made or if an entry which appears to be valid is actually found to be faulty such as when a particular file can not be found.

The same concept should be applied to all aspects of your Console application. The bottom line is, you created the application so you know what is expected however the same can not be said for someone that is to use your application. They have absolutely no clue what is expected.

As for the task at hand, you are expected to utilize code and concepts you've already learned and for those that you haven't already learned by doing research and experimentation with other algorithmic code concepts. Along the way you will hopfuly pick up some degree of "Thinking Out Of The Box" and this trait will actually become natural with the more code and concepts you eventually learn.

Write down a methodical plan of attack for accomplishing the task. This can save you an immense amount of grief down the road as your code progresses, for example:

  • Explain Application;
  • Ask User for a File Name;
    • Make sure a file name was supplied;
      • If not then ask for file name again;
    • Make sure the file exists;
      • If not then ask for file name again;
  • Ask the User for a Output file name;
    • See if the file already exists;
      • Ask to Overwrite if it does;
      • If Not to overwrite then ask for another Output file name;
  • Open a Reader to read the file name supplied;
  • Open a Writer to write results to specified file name;
  • Read each file line using a while loop;
    • Split each read in line to String Array with String.split( "\\\\s+" ) method;
    • Declare a totalSum variable as double data type;
    • Declare a average variable as double data type;
    • Iterate through String Array with for loop;
      • Make sure each Array element is a decimal value using the String#matches( "-?\\\\d+(\\\\.\\\\d+)" ) method;
      • Convert each array element to double and add to **totalSum*;
    • After for loop divide totalSum by the number of elements in array to get average, place this amount into average variable;
    • Write to file: "Average for: " + fileLine + " is: " + average. Also display to console;
  • After entire file is processed close Reader and close Writer.
  • DONE.

This would now be your basic guide to creating your application.

When reading data files with Scanner I feel it's best to use the Scanner#hasNextLine() method within the while loop condition rather than the Scanner#hasNext() method since this method is more focused on acquiring tokens rather than file lines. So this would be a better approach in my opinion:

String outFile = "";
// Write code to get the File Name to write to and place 
// it into the the variable outFile ....
File outputFile = new File(outFile); // True file name is acquired from User input
if (outputFile.exists()) {
    // Ask User if he/she wants to overwrite if file exists....and so on
}

// 'Try With Resourses' on reader
try (Scanner reader = new Scanner(file)) {
    // 'Try With Resourses' on writer
    try (PrintWriter writer = new PrintWriter(outputFile)) {
        String line = "";
        while (reader.hasNextLine()) {
            line = reader.nextLine().trim();
            // Skip blank lines (if any)
            if (line.equals("")) {
                continue;
            }
            // Split the data line into a String Array
            String[] data = line.split("\\s+"); // split data on one or more whitespaces
            double totalSum = 0.0d;  // Hold total of all values in data line
            double average = 0.0d;   // To hold the calculated avarage for data line
            int validCount = 0;      // The amount of valid data values on data line (used as divisor)
            // Iterate through data Line values String Array
            for (int i = 0; i < data.length; i++) {
                // Is current array element a string representation of
                // a decimal value (signed or unsigned)
                if (data[i].matches("-?\\d+(\\.\\d+)")) {
                    // YES!...add to totalSum
                    validCount++;
                    // Convert Array element to double then add to totalSum.
                    totalSum += Double.parseDouble(data[i]); 
                }
                else {
                    // NO! Kindly Inform User and don't add to totalSum.
                    System.out.println("An invalid value (" + data[i] + ") was detected within "
                            + "the file line: " + line);
                    System.out.println("This invalid value was ignored during                                   + "averaging calculations!" + System.lineSeparator());
                }
            }
            // Calculate Data Line Average
            average = totalSum / validCount;
            // Write the current Data Line and its' determined Average
            // to the desired file (delimited with the Pipe (|) character.
            writer.append(line + " | Average: " + String.valueOf(average) + System.lineSeparator());
            writer.flush();
        }
    }
    System.out.println("DONE! See the results file.");
}
// Catch the fileNotFound exception
catch (FileNotFoundException ex) {
    ex.printStackTrace();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM