Question: I have this code but, it doesn't work package test; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.LinkedList; import java.util.Scanner; public class test
I have this code but, it doesn't work
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Scanner;
public class test {
public static void main(String[]args) throws IOException {
Scanner sc = new Scanner(System.in);//To read user input
String fileName = sc.nextLine();
while(!new File(fileName).exists()) {//Read until a valid name is provided
System.out.println( "File 'somefile.txt' is not found. Please enter correct file name");
fileName = sc.nextLine();
}
LinkedList
if (list.isEmpty()) {//if file empty, exit the program
System.out.println("File 'somefile.txt' is empty.");
System.exit(0);
}
for(int i = 0; i < list.size(); i++) {//for every element
if(list.get(i).equalsIgnoreCase(list.get(list.size() - i - 1))) {//check i pos from last is same
System.out.println(list.get(i) + "found at " + (list.size() - i - 1));
list.set(i, "");//to avoid duplicate check
sc.close();
}
}
}
public static LinkedList
BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));//file reader
String line = null;
LinkedList
try {
while ((line = reader.readLine()) != null) {
list.add(line);
}
} finally {
reader.close();
}
return list;
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
