Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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 list = readData(fileName);//Read user file data into list

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 readData(String fileName) throws IOException {

BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));//file reader

String line = null;

LinkedList list = new LinkedList();//list to hold names

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions

Question

Discuss all branches of science

Answered: 1 week ago