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 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 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: 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...
write program in java Create a class named PersonalDetails with the fields name and address. The...
write program in java Create a class named PersonalDetails with the fields name and address. The class should have a parameterized constructor and get method for each field.  Create a class named Student with the fields ID, PersonalDetails object, major and GPA. The class should have a parameterized constructor and get method for each field. Create an application/class named StudentApp that declare Student object. Prompts (GUI input) the user for student details including ID, name, address, major and GPA....
10) Create a java program that will ask for name and age with method age where...
10) Create a java program that will ask for name and age with method age where it will check the condition that id you are greater than 18 you can vote.
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...
Write the code in Java: 1. Create a method that displays your name in the console....
Write the code in Java: 1. Create a method that displays your name in the console. This method is void and takes no parameters. Make an app that runs the method in response to a button press. 2. Create a version of the method in #1 that takes the text (String) to be displayed as a parameter. Allow the user to enter the text in a dialog box or text field and display that text in the console. Be sure...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT