Question

In: Computer Science

JAVA single method Loop (for beginner) Name your class LoopsFiles Create a program that reads a...

  • JAVA single method Loop (for beginner)
  • Name your class LoopsFiles
  • Create a program that reads a list of names from a source file and writes those names to a CSV file.
  • The source file name and target CSV file name should be requested from the user
  • The source file can have a variable number of names so your program should be dynamic enough to read as many names as needed
  • When writing your CSV file, the first row (header row) should be “Number, Name”.
  • The final CSV should have the header row and a row with the sequential number, name read.
  • The program should display an error message if the source file doesn’t exist.
  • If the destination file exists the program should warn the user and prompt the user if they want to overwrite the existing file (Y/N).
    • The user should be prompted until they enter Y for yes to overwrite, or enter a unique name after answering N for the overwrite prompt.
  • Submit your single .java file

Source file example:

John
Peter
Jane
Mary
Evelyn
Daniel

New CSV File example:

Number, Name
1,John
2,Peter
3,Jane
4,Mary
5,Evelyn
6,Daniel

Example Scenario 1 – Normal run:

Enter source file name: source.txt
Enter destination file name: destination.csv
Your file is ready!

Example Scenario 2 – File doesn’t exist:

Enter source file name: source.txt
Enter destination file name: destination.csv
Source file doesn’t exist!

Example Scenario 3 – Target file already exists (overwrite):

Enter source file name: source.txt
Enter destination file name: destination.csv
Target file already exists. Overwrite existing file? (Y/N): N
Enter destination file name: destination.csv
Target file already exists. Overwrite existing file? (Y/N): N
Enter destination file name: destination.csv
Target file already exists. Overwrite existing file? (Y/N): N
Enter destination file name: destination.csv
Target file already exists. Overwrite existing file? (Y/N): Y
Your file is ready!

Example Scenario 4 – Target file already exists (new name given):

Enter source file name: source.txt
Enter destination file name: destination.csv
Target file already exists. Overwrite existing file? (Y/N): N
Enter destination file name: destination.csv
Target file already exists. Overwrite existing file? (Y/N): N
Enter destination file name: destination2.csv
Your file is ready!

Solutions

Expert Solution

Please find the code below:

import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;

public class LoopsFiles {

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

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter source file name: ");
        String source = sc.next();
        ArrayList<String> arrayList = new ArrayList<>();
        try {
            File file = new File(source);
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String data = scanner.nextLine();
                arrayList.add(data);
                System.out.println(data);
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("Source file doesn’t exist!");
            e.printStackTrace();
        }

        while(true) {

            System.out.println("Enter destination file name: ");
            String destination = sc.next();

            File file = new File(destination);

            if (file.createNewFile()) {

                System.out.println("File has been created.");
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fileOutputStream));

                bw.write("Number,Name");
                bw.newLine();
                for (int i=1;i<=arrayList.size();i++) {
                    String temp = i + "," + arrayList.get(i-1);
                    System.out.println(temp);
                    bw.write(temp);
                    bw.newLine();
                }

                System.out.println("Your file is ready!");
                break;

            } else {

                System.out.println("Target file already exists. Overwriting existing file? (Y/N):");
                String inp = sc.next();

                if(inp.equals("N")) {
                    continue;
                }
                else {
                    System.out.println("File has been created.");
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fileOutputStream));

                    bw.write("Number,Name");
                    bw.newLine();
                    for (int i=1;i<=arrayList.size();i++) {
                        String temp = i + "," + arrayList.get(i-1);
                        System.out.println(temp);
                        bw.write(temp);
                        bw.newLine();
                    }

                    System.out.println("Your file is ready!");
                    break;
                }

            }

        }

    }
}

Related Solutions

Program in Java Create a class and name it MyArray and implement following method. * NOTE:...
Program in Java Create a class and name it MyArray and implement following method. * NOTE: if you need more methods, including insert(), display(), etc. you can also implement those. Method name: getKthMin(int k) This method receives an integer k and returns k-th minimum value stored in the array. * NOTE: Items in the array are not sorted. If you need to sort them, you can implement any desired sorting algorithm (Do not use Java's default sorting methods). Example: Items...
Program in Java Create a class and name it MyArray and implement following method. * NOTE:...
Program in Java Create a class and name it MyArray and implement following method. * NOTE: if you need more methods, including insert(), display(), etc. you can also implement those. Method name: getKthMin(int k) This method receives an integer k and returns k-th minimum value stored in the array. * NOTE: Items in the array are not sorted. If you need to sort them, you can implement any desired sorting algorithm (Do not use Java's default sorting methods). Example: Items...
Write a Java program (single file/class) whose filename must be Numbers.java. The program reads a list...
Write a Java program (single file/class) whose filename must be Numbers.java. The program reads a list of integers from use input and has the following methods: 1. min - Finds the smallest integer in the list. 2. max- Finds the largest integer in the list. 3. average - Computes the average of all the numbers. 4. main - method prompts the user for the inputs and ends when the user enter Q or q and then neatly outputs the entire...
*Java program* Use while loop 1.) Write a program that reads an integer, and then prints...
*Java program* Use while loop 1.) Write a program that reads an integer, and then prints the sum of the even and odd integers. 2.) Write program to calculate the sum of the following series where in is input by user. (1/1 + 1/2 + 1/3 +..... 1/n)
Java Programming Create a class named Problem1, and create a main method, the program does the...
Java Programming Create a class named Problem1, and create a main method, the program does the following: - Prompt the user to enter a String named str. - Prompt the user to enter a character named ch. - The program finds the index of the first occurrence of the character ch in str and print it in the format shown below. - If the character ch is found in more than one index in the String str, the program prints...
Java: Create a class and name it MyArray and implement following method. * NOTE: if you...
Java: Create a class and name it MyArray and implement following method. * NOTE: if you need more methods, including insert(), display(), etc. you can also implement those Method name: getKthMin(int k) This method receives an integer k and returns k-th minimum value stored in the array. * NOTE: Items in the array are not sorted. If you need to sort them, you can implement any desired sorting algorithm (Do not use Java's default sorting methods). Example: Items in the...
Java program Create a public method named saveData for a class named Signal that will hold...
Java program Create a public method named saveData for a class named Signal that will hold digitized acceleration data. Signal has the following field declarations private     double timeStep;               // time between each data point     int numberOfPoints;          // number of data samples in array     double [] acceleration = new double [1000];          // acceleration data     double [] velocity = new double [1000];        // calculated velocity data     double [] displacement = new double [1000];        // calculated disp...
2. Create a java program that reads a file line by line and extract the first...
2. Create a java program that reads a file line by line and extract the first word.        The program will ask for the name of input and output file. Input file: words.txt today tomorrow sam peterson peter small roy pratt Output file: outwords.txt tomorrow peterson small pratt
Create a java class with name Cat. Instructions for Cat class: This class is modeled after...
Create a java class with name Cat. Instructions for Cat class: This class is modeled after a Cat. You should have instance variables as follows: The Cat’s name The number of mice caught by the Cat. Whether or not the Cat is secretly plotting to kill you Note that you will need to choose both good types and meaningful identifiers for each of these instance variables. You may also assume that the Cat is not automatically always secretly plotting to...
In java program format Submit your completed UML class diagram and Java file. Part I: Create...
In java program format Submit your completed UML class diagram and Java file. Part I: Create a UML diagram for this assignment PartII: Create a program that implements a class called  Dog that contains instance data that represent the dog's name and age.   define the Dog constructor to accept and initialize instance data.   create a method to compute and return the age of the dog in "person-years" (note: dog age in person-years is seven times a dog's age).   Include a toString...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT