Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need some help with some basic java programming questions. For all questions,

ID: 670845 • Letter: I

Question

I need some help with some basic java programming questions. For all questions, only the code needed to do the action requested is required, not full programs.

1. File info

was defined in previous code. Write the code that, if the file is a directory, prints the message 'Exists'; otherwise, print the message 'Does not exist.'

2. An ArrayList is declared like so:

Students have already been initialized and had values added to the ArrayList. Write code that will, for each element in the ArrayList, display the element and then the string length of the element on the line.

e.g., if the ArrayList had "John", "Matthew", and "Eric" in it, then it would display:

3. Write code that creates a file named scores.txt, which then puts the string 'John 75 .8' into the file, followed by the string 'Eric 80 3.2' into the file and then closes the file.

4. Complete the code to create a File object for the path

/programming/answer/answeris

Thank you!

Explanation / Answer

import java.io.*;
import java.util.*;


class main{
   public static void main(String[] args){
       // Question 1
       Bufferedreader br = null;
       Scanner sc = new Scanner(System.in);
       System.out.println("Enter the file name : ");
       String file_name = sc.nextLine();
       try{
           br = new Bufferedreader(new FileReader(file_name));
           System.out.println("Exist");
       }  
       catch (IOException e) {
           System.out.println("Does not Exist");
       }

       // Question 2
       ArrayList<String> ar = ArrayList<String>();
       ar.add("John"); ar.add("Matthew"); ar.add("Eric");
       for (int i = 0; i < ar.size(); i++)
           System.out.println(ar.get(i)+" "+ar.get(i).length());
  
       // Question 3
       File file = new File("scores.txt");
      
       if (!file.exists())
           file.createNewFile();
       FileWriter fw = new FileWriter(file.getAbsoluteFile());
       BufferedWriter bw = new BufferedWriter(fw);
  
       bw.write("John 75 .8 ");
       bw.write("Eric 80 3.2 ");
       bw.close();


       // Question 4
       file = new File("/programming/answer/answeris/scores.txt");
      
       if (!file.exists())
           file.createNewFile();
       fw = new FileWriter(file.getAbsoluteFile());
       bw = new BufferedWriter(fw);
  
       bw.write("John 75 .8 ");
       bw.write("Eric 80 3.2 ");
       bw.close();


   }
}