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

HELP PLS! or ANY HINTS! Running myMain prompts the user for two files, then atta

ID: 3598047 • Letter: H

Question

HELP PLS! or ANY HINTS!

Running myMain prompts the user for two files, then attach each file to a scanner and pass the scanners to a class called anotherMain.
Write a static main method in a class called myMain. Main should prompt the name of the first file and once it has a valid name it should prompt for the name of second file. If the file does not exist or types a file that does exist but results in an error when read by anotherMain, main should report the error and give the user to try the file name again. Write a private helper method that takes a prompt as a parameter and returns a Scanner. The method should repeatedly prompt the user until it is is able to open the user response as a file and connect a Scanner to it.

Explanation / Answer

Given below is the code . The functionality of anotherMain is not explained in detail in the question. I have code anotherMain to read the file passed as scanner.

To indent code in eclipse, press Ctrl+A in the file and then press Ctrl+i

To provide input files , place the files directly under project and NOT inside src folder.

Please don't forget to rate the answer if it helped. Thank you


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class myMain {
private static Scanner keybd = new Scanner(System.in);
private static Scanner getFile(String prompt)
{
while(true)
{
System.out.println(prompt);
String filename = keybd.nextLine(); //get filename from user
try {
//try to create a scanner object
Scanner file = new Scanner(new File(filename));
return file; //success return file
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args) {

Scanner file = getFile("Enter first filename: " );
anotherMain.read(file);
file = getFile("Enter second filename: ");
anotherMain.read(file);
}
}


import java.util.Scanner;
public class anotherMain {
public static void read(Scanner file)
{
while(file.hasNextLine())
System.out.println(file.nextLine());
}
}

output of myMain.java


Enter first filename:
abc.txt
abc.txt (No such file or directory)
Enter first filename:
planets.txt
Mercury 57910000.0 4880.0 3.30e23
Venus 108200000.0 12103.6 4.869e24
Earth 149600000.0 12756.3 5.972e24
Mars 227940000.0 6794.0 6.4219e23
Jupiter 778330000.0 142984 1.900e27
Saturn 1429400000.0 120536 5.68e26
Uranus 2870990000.0 51118.0 8.683e25
Neptune 4504000000.0 49532.0 1.0247e26
Pluto 5913520000.0 2274.0 1.27e22
Enter second filename:
dkfsdfks
dkfsdfks (No such file or directory)
Enter second filename:
eeiie
eeiie (No such file or directory)
Enter second filename:
scores.txt
john 7
alice 6
bob 7
michael 7