Radix Sort- Calling Expected exceptions - java

I am working on a program that uses Radix Sort that reads in words from a file and sorts in ascending order. In order to do this, we must check that all the words in the file are the same length and there is nothing in the file but letter (no symbols, etc). I have the sort working, but I cannot catch whether the strings are the same length or if there are any symbols. Any help on how to write these exception catches would be appreciated.
This is my radix Sort class. There are two comments on where I need to catch the exceptions.
import java.util.ArrayList;
import java.util.Queue;
public class RadixSort implements RadixSortADT {
private ArrayList<String> string;
private ArrayList<LinkedQueue<String>> queues;
private String result;
public RadixSort(ArrayList<String> words) {
string = new ArrayList<>();
queues = new ArrayList<>();
initializeList();
initializeWords(words);
}
public void initializeList() {
for(int i = 0; i < 26; i++){
queues.add(new LinkedQueue<String>());
}
}
public void initializeWords(ArrayList<String> w) {
for(int i = 0; i < w.size(); i++){
string.add(w.get(i).toLowerCase());
}
}
public void sort() {
if(string.isEmpty()){
throw new EmptyCollectionException("File");
}
//Exception needed for string length comparisons
//Exception needed for nonletters in string
for(int j = string.get(0).length()-1; j>= 0; j--){
for(int k = 0; k <string.size(); k++){
char c = string.get(k).charAt(j);
queues.get(c-97).enqueue(string.get(k));
}
int i = 0;
for(int n = 0; n <queues.size(); n++){
while(!queues.get(n).isEmpty()){
string.set(i++, queues.get(n).dequeue());
}
}
}
}
public String toString(){
String result = "";
for(String words: string){
result += words + " ";
}
return result;
}
public boolean isAlpha(ArrayList<String> string2) {
return string2.contains("[a-zA-Z]+");
}
}
This is the driver that was provided for me in order to create the Radix Sort class
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class RadixSortDriver {
public static void main(String[] args) throws FileNotFoundException{
int i = 0;
ArrayList<String> words = new ArrayList<>();
Scanner scan = new Scanner(System.in);
System.out.println("Enter the name of the file to import words");
String filename = scan.nextLine();
//String filename = "four.txt";
Scanner inFile = new Scanner(new File(filename));
while(inFile.hasNext()) {
words.add(inFile.nextLine());
}
RadixSort r = new RadixSort(words);
System.out.println("Unsorted List:\n" + r);
r.sort();
System.out.println("\n\nSorted List:\n" + r);
}
}
This is the Junit Test class that was provided for us in order to catch the exceptions
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import org.junit.Test;
public class RadixSortTest {
#Test
public void testsort1() throws FileNotFoundException {
ArrayList<String> words = new ArrayList<>();
Scanner inFile = new Scanner(new File("four.txt"));
while(inFile.hasNext()) {
words.add(inFile.nextLine());
}
RadixSort evaluator = new RadixSort(words);
evaluator.sort();
assertEquals("atom barn crew goat home kite love rain soap xray yarn ", evaluator.toString());
}
#Test
public void testsort5() throws FileNotFoundException {
ArrayList<String> words = new ArrayList<>();
Scanner inFile = new Scanner(new File("fourUpper.txt"));
while(inFile.hasNext()) {
words.add(inFile.nextLine());
}
RadixSort evaluator = new RadixSort(words);
evaluator.sort();
assertEquals("atom barn crew goat home kite love rain soap xray yarn ", evaluator.toString());
}
#Test(expected=EmptyCollectionException.class)
public void testsort7() throws FileNotFoundException {
ArrayList<String> words = new ArrayList<>();
Scanner inFile = new Scanner(new File("empty.txt"));
while(inFile.hasNext()) {
words.add(inFile.nextLine());
}
RadixSort evaluator = new RadixSort(words);
evaluator.sort();
fail("Empty list Exception not caught");
}
#Test(expected=InvalidRadixSortException.class)
public void testsort10() throws FileNotFoundException {
ArrayList<String> words = new ArrayList<>();
Scanner inFile = new Scanner(new File("error3.txt"));
while(inFile.hasNext()) {
words.add(inFile.nextLine());
}
RadixSort evaluator = new RadixSort(words);
evaluator.sort();
fail("Invalid Length Exception not caught");
}
}
Finally, this is the exception class that was created so we knew what exception to call
public class InvalidRadixSortException extends RuntimeException
{
/**
* Sets up this exception with an appropriate message.
* #param collection the name of the collection
*/
public InvalidRadixSortException(String error)
{
super("The list of words contained an invalid " + error);
}
}

Use this method to throw exceptions:
private void validateWords() {
int length = string.get(0).length();
for (int j = 0; j < string.size(); j++) {
if (string.get(j).length() != length) {
throw new InvalidRadixSortException("Invalid String Length");
}
if (!string.get(j).matches("[a-zA-Z]+")) {
throw new InvalidRadixSortException("Contains Non-Letters");
}
}
}

Related

Is there any logic to compare two word documents(docx) and catch the missing String, Special chars, space and all the stuff?

I'm working on two word document comparison manually where i should not miss any Strings, Special chars, space and all the stuff and that document is around 150 pages or more. so its very headache to do comparison. Then I have written small java program to compare two documents but I'm not able to list the missing words.
Using Apche POI Library
Thanks in advance.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFFooter;
import org.apache.poi.xwpf.usermodel.XWPFHeader;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
public class ReadDocFile {
private static XWPFDocument docx;
// private static String path = "C:\\States wise\\NH\\Assessment
// 2nd\\test.docx";
private static ArrayList<String> firstList = new ArrayList<String>(); // refers to first document list
private static ArrayList<String> secondList = new ArrayList<String>(); // refers to second document list
private static List<XWPFParagraph> paragraphList;
private static Map<String, String> map = null;
private static LinkedHashSet<String> firstMissedArray = new LinkedHashSet<String>(); // refers to first document Linked hash set
private static LinkedHashSet<String> secondMissedArray = new LinkedHashSet<String>(); // refers to second document Linked hash set
public static void getFilePath(String path) {
FileInputStream fis;
try {
fis = new FileInputStream(path);
docx = new XWPFDocument(fis);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void get_First_Doc_Data() {
getFilePath("C:\\States wise\\NH\\Assessment 2nd\\test.docx");
paragraphList = docx.getParagraphs();
System.out.println("******************** first list Starts here ******************** ");
System.out.println();
for (int i = 0; i < paragraphList.size() - 1; i++) {
firstList.add(paragraphList.get(i).getText().toString());
System.out.println(firstList.get(i).toString());
}
System.out.println("*********** first list Ends here ********************");
}
public static void get_Second_Doc_Data() {
getFilePath("C:\\States wise\\NH\\Assessment 2nd\\test1.docx");
paragraphList = docx.getParagraphs();
System.out.println("******************** Second list Starts here ******************** ");
System.out.println();
for (int i = 0; i < paragraphList.size() - 1; i++) {
secondList.add(paragraphList.get(i).getText().toString());
System.out.println(secondList.get(i).toString());
}
System.out.println("*********** Second list Ends here ********************");
}
public static void main(String[] args) {
get_First_Doc_Data();
get_Second_Doc_Data();
//System.out.println("First Para: " + firstList.contains(secondList));
compare();
compare_Two_List();
}
private static void compare() {
String firstMiss = null;
//String secondMiss = null;
for (int i = 0; i < firstList.size(); i++) {
for (int j = 0; j < secondList.size(); j++) {
if (!firstList.get(i).toString().equals(secondList.get(i).toString())) {
firstMiss = firstList.get(i).toString();
//secondMiss = secondList.get(i).toString();
map = new HashMap<String, String>();
}
}
firstMissedArray.add(firstMiss);
//secondMissedArray.add(secondMiss);
// System.out.println(missedArray.get(i).toString());
}
}
private static void compare_Two_List() {
int num = 0;
map.clear();
Iterator<String> first = firstMissedArray.iterator();
//Iterator<String> second = secondMissedArray.iterator();
while (first.hasNext()) {
map.put(""+num, first.next());
num++;
}
System.out.println(firstMissedArray.size());
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
// it.remove(); // avoids a ConcurrentModificationException
}
}
}
I have taken liberty to modify your code to arrive at the solution for your problem. Please go through this.
This should pretty much solve your problem - put SYSO statements wherever you think is necessary and tweak the flow of the program to achieve desired checks as per you requirement. In my hurry, I may not have made use of coding standards of using try catch block for error handling and handling the negative scenarios, so please take care of that when implementing it live.
In case if the documents are not .DOCX but .PDF make use of the Apache PDFBox api.
Here is the Code:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
public class Comapre_Docs {
private static final String FIRST_DOC_PATH = "E:\\Workspace_Luna\\assignments\\Expected.docx";
private static final String SECOND_DOC_PATH = "E:\\Workspace_Luna\\assignments\\Actual.docx";
private static XWPFDocument docx;
private static List<XWPFParagraph> paragraphList;
private static ArrayList<String> firstList = new ArrayList<String>();
private static ArrayList<String> secondList = new ArrayList<String>();
public static void get_Doc_Data(String filePath, ArrayList listName)
throws IOException {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
docx = new XWPFDocument(fis);
paragraphList = docx.getParagraphs();
for (int i = 0; i <= paragraphList.size() - 1; i++) {
listName.add(paragraphList.get(i).getText().toString());
}
fis.close();
}
public static void main(String[] args) throws IOException {
get_Doc_Data(FIRST_DOC_PATH, firstList);
get_Doc_Data(SECOND_DOC_PATH, secondList);
compare(firstList, secondList);
}
private static void compare(ArrayList<String> firstList_1,
ArrayList<String> secondList_1) {
simpleCheck(firstList_1, secondList_1);
int size = firstList_1.size();
for (int i = 0; i < size; i++) {
paragraphCheck(firstList_1.get(i).toString().split(" "),
secondList_1.get(i).toString().split(" "), i);
}
}
private static void paragraphCheck(String[] firstParaArray,
String[] secondParaArray, int paraNumber) {
System.out
.println("=============================================================");
System.out.println("Paragraph No." + (paraNumber + 1) + ": Started");
if (firstParaArray.length != secondParaArray.length) {
System.out.println("There is mismatch of "
+ Math.abs(firstParaArray.length - secondParaArray.length)
+ " words in this paragraph");
}
TreeMap<String, Integer> firstDocPara = getOccurence(firstParaArray);
TreeMap<String, Integer> secondDocPara = getOccurence(secondParaArray);
ArrayList<String> keyData = new ArrayList<String>(firstDocPara.keySet());
for (int i = 0; i < keyData.size(); i++) {
if (firstDocPara.get(keyData.get(i)) != secondDocPara.get(keyData
.get(i))) {
System.out
.println("The following word is missing in actual document : "
+ keyData.get(i));
}
}
System.out.println("Paragraph No." + (paraNumber + 1) + ": Done");
System.out
.println("=============================================================");
}
private static TreeMap<String, Integer> getOccurence(String[] paraArray) {
TreeMap<String, Integer> paragraphStringCountHolder = new TreeMap<String, Integer>();
paragraphStringCountHolder.clear();
for (String a : paraArray) {
int count = 1;
if (paragraphStringCountHolder.containsKey(a)) {
count = paragraphStringCountHolder.get(a) + 1;
paragraphStringCountHolder.put(a, count);
} else {
paragraphStringCountHolder.put(a, count);
}
}
return paragraphStringCountHolder;
}
private static boolean simpleCheck(ArrayList<String> firstList,
ArrayList<String> secondList) {
boolean flag = false;
if (firstList.size() > secondList.size()) {
System.out
.println("There are more paragraph in Expected document than in Actual document");
} else if (firstList.size() < secondList.size()) {
System.out
.println("There are more paragraph in Actual document than in Expected document");
} else if (firstList.size() == secondList.size()) {
System.out.println("The paragraph count in both documents match");
flag = true;
}
return flag;
}
}

Array contains null values

I was trying to read some words from a text file and then arrange them into descending array.
I reached the point where I read the words successfully,stored the words in a array, and when I went ahead to arrange it into descending form I noticed that my array also contained some null values.
When I tried to remove the null values using (complete code below)
Arrays.stream(w.words).filter(x->x != null).toArray(); , it still didn't worked.
After trying for quite some time now I think I need some help here.
Code,text file and output at this stage is as follows:
`
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.stream.Collectors;
public class Practise {
private Scanner fp;
private Scanner scanLine;
private String[] words = new String[6] ;
int count;
String temp;
String [][] samewords;
int size;
String[] words_sorted;
public Practise() {
openFile();
readFile();
printa();
}
private void openFile() {
try {
fp = new Scanner(new File ("D:\\workspace\\file.txt"));
}
catch (Exception e) {
System.out.println("File does not exist");
}
}
private void readFile() {
try {
count = 0;
while (fp.hasNextLine()) {
String strLine = fp.nextLine();
scanLine = new Scanner(strLine);
words[count] = scanLine.next();
System.out.println("Here2"+words[count]);
System.out.println();
count++;
}
}
catch (Exception e) {
System.err.print("Error: " + e.getMessage());
}
}
private void printa() {
try (BufferedReader br = new BufferedReader(new FileReader("D:\\workspace\\file.txt"))) {
size = findLongestWords();
samewords = new String[size][size];
String line;
int i = 0;
String [] temp;
while ((line = br.readLine()) != null) {
temp = line.split(",");
for (int j = 0; j < samewords[i].length; j++) {
samewords[i][j] = temp[j];
System.out.println(samewords[i][j]);
}
i++;
}
//System.out.println(answers[1][2]);
} catch (IOException e) {
e.printStackTrace();
}
}
public int findLongestWords() throws FileNotFoundException {
int longest_word = 0;
int current;
BufferedReader sc = new BufferedReader(new FileReader("D:\\workspace\\file.txt"));
String li;
String[] tr;
try {
while ((li = sc.readLine())!= null ) {
tr = li.split(",");
current = tr.length;
if (current > longest_word) {
longest_word = current;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("\n"+longest_word+"\n");
return longest_word;
}
private String[] sort(String[] string) {
/*Local variables*/
Map<String, Integer> map=new LinkedHashMap<String, Integer>();
Map<String, Integer> mapCopy=new LinkedHashMap<String, Integer>();
int [] lengthsArray=new int[string.length];
String [] sortedStrings=new String[string.length];
int counter1=0;
int counter2=0;
/* Store all the pairs <key,value>
* i.e <string[i],string[i].length>
*/
for(String s:string) {
System.out.println(s);
map.put((String) s, s.length());
lengthsArray[counter1]= s.length();//store all the lengths
counter1++;
}
mapCopy=new LinkedHashMap<String, Integer>(map);//make a copy of map
Arrays.sort(lengthsArray);//sort the array of lengths
/*
* Sort array according to the array of lengths
* by finding the matching value from the map
* then add it to the final string array,and then remove it from the map
*/
for(int item:lengthsArray) {
for(Map.Entry<String, Integer> e:map.entrySet()) {
if(item==e.getValue()) {
sortedStrings[counter2]=e.getKey();
counter2++;
map.remove(e.getKey());
break;
}
}
}
map=mapCopy;
System.out.println(map);//print map
return sortedStrings;
}
public static void main(String[] args) {
Practise w = new Practise();
System.out.println(Arrays.toString(w.words));
w.sort(w.words);
}
}
`
file.txt is:
ACT,CAT,AT,RAT,PAT,TAT
output is:
Here2ACT,CAT,AT,RAT,PAT,TAT
6
ACT
CAT
AT
RAT
PAT
TAT
[ACT,CAT,AT,RAT,PAT,TAT, null, null, null, null, null]
ACT,CAT,AT,RAT,PAT,TAT
null
Exception in thread "main" java.lang.NullPointerException
at Practise.sort(Practise.java:190)
at Practise.main(Practise.java:239)
null is because of the word array which you have declared ( predefined size ). Probably you can change that and use ArrayList (as it can be of dynamic size) instead of an String array, which can help you resolve. Just to help you, follow below changes:
private List<String> words = new ArrayList<>();
/*update below line in readFile() instead of words[count] = scanLine.next();*/
words.add(scanLine.next());
Change method signature sort(List<String> string)
//also update below declarations
int[] lengthsArray = new int[string.size()];
String[] sortedStrings = new String[string.size()];
change Arrays.toString(w.words) to just w.words in print statement
Hope this helps. Everything looks good.

Can't read files from command line. The files are in the same folder. FileNotFountException

I am writing this to take in data about books from a txt file. (ISBN, Price, Stock) I keep running into FileNotFoundException problems and cant figure out where the problem is. Sorry if the code is bad or whatever i'm still very now to programming.
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
import java.io.FileNotFoundException;
import java.io.File;
public class BookInventory {
static ArrayList ISBN = new ArrayList();
static ArrayList Price = new ArrayList();
static ArrayList Stock = new ArrayList();
public static void main(String[] args)throws FileNotFoundException{
if(handleArgs(args)){
for(int j = 0; j < args.length; j++){
getInventory(args, j);
}
}
}
public static void getInventory(String[]args, int j)throws FileNotFoundException{
Scanner input = null;
try {
File inputFile = new File(args[j]);
Scanner booksFile = new Scanner(inputFile);
if(booksFile.hasNextDouble()){
while (booksFile.hasNext()) {
try {
ISBN.add(booksFile.next());
Price.add(booksFile.next());
Stock.add(booksFile.next());
} catch (java.util.InputMismatchException ex) {
throw ex;
}
}
}
} catch (FileNotFoundException ex) {
System.out.println("Error: File " + args[j] + " not found. Exiting program.");
System.exit(1);
}
}
public static boolean handleArgs(String[]args){
if(args.length < 2){
System.out.println("Incorrect number of command line arguments.");
System.out.println("Program requires at least 2 files.");
return false;
}
return true;
}
}

Project compiles but not displaying info in compiler

Hey I'm making a program that takes words+definitions from a text document, scrambles them, then quizzes you on them. The words are structured as (word: definition). I finished the code for the project but for some reason the console stays blank after I compile. The code consists of three classes that I'll display below:
Class 1 :-
public class VocabularyWord {
private String word, definition;
public VocabularyWord(String w, String d){
word=w;
definition=d;
}
public String getDefinition(){
return definition;
}
public String getWord(){
return word;
}
public String toString(){
return word+" "+definition;
}
}
Class 2 :-
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class VocabularyTest {
private ArrayList<VocabularyWord>words;
private int c;
public VocabularyTest() throws FileNotFoundException{
words=new ArrayList<VocabularyWord>();
ArrayList<String> str=new ArrayList<String>();
File inputFile = new File("Vocabulary.txt");
Scanner input = new Scanner(inputFile);
while(input.hasNextLine()){
str.add(input.nextLine());
processStrings(str);
for(int i = 0; i<100; i++)
swapWords();
}
}
private void processStrings(ArrayList<String>lines){
int pos=0;
for(int i=lines.size()-1; i>=0; i--){
pos=lines.get(i).indexOf(":");
String s=lines.get(i).substring(0, pos);
String ss=lines.get(i).substring(pos+1, lines.get(i).length());
VocabularyWord p=new VocabularyWord(s,ss);
words.add(p);
c++;
}
}
private void swapWords(){
int x=(int) (Math.random()*words.size());
int xx=(int)(Math.random()*words.size());
while(x==xx)
xx=(int)(Math.random()*words.size());
Collections.swap(words, xx, x);
}
public void quiz(){
System.out.println("hi");
int n=0;
Scanner kb=new Scanner(System.in);
for(int i=words.size()-1; i>=0; i--){
System.out.println(words.get(i).getDefinition());
if(kb.nextLine().equals(words.get(i).getWord())){
System.out.println("Nice Job!");
n++;
}
else
System.out.println(words.get(i).getWord());
}
System.out.println("You got "+n+" correct!");
}
}
Class 3 :-
import java.io.FileNotFoundException;
public class VocabTestTester {
public static void main(String[] args)throws FileNotFoundException{
VocabularyTest test= new VocabularyTest();
test.quiz();
}
}
I'm guessing that your VocabularyTest constructor is failing, possibly that you're not finding the file adequately, although I'd expect to see an exception from this. You'd do well to check this.
Print "hi" on the first line of the VocabularyTest constructor, print out the file path, and check that it matches the path that you expect, and then print out the words read in to the console.
e.g.,
public VocabularyTest() throws FileNotFoundException{
System.out.println("In VocabularTest Constructor");
words=new ArrayList<VocabularyWord>();
ArrayList<String> str=new ArrayList<String>();
File inputFile = new File("Vocabulary.txt");
System.out.println(inputFile.getAbsolutePath());
Scanner input = new Scanner(inputFile);
while(input.hasNextLine()){
System.out.println(input.nextLin());
}

Trying to read a text file using regex to check each line

I am trying to write a program that will allow a user to input a name of a movie and the program would then generate the date associated with. I have a text file that has date and the movies that pertain to it. I am reading the file via Scanner and I created a movie class that stores an ArrayList and String for movies and date, respectively. I am having trouble with reading the files. Can anyone please assist me. Thank you!
Here is a part of the text file:
10/1/2014
Der Anstandige
"Men, Women and Children"
Nas: Time is Illmatic
10/2/2014
Bang Bang
Haider
10/3/2014
Annabelle
Bitter Honey
Breakup Buddies
La chambre bleue
Drive Hard
Gone Girl
The Good Lie
A Good Marriage
The Hero of Color City
Inner Demons
Left Behind
Libertador
The Supreme Price
Here is my movie class
import java.util.ArrayList;
public class movie
{
private ArrayList<String> movies;
private String date;
public movie(ArrayList<String> movies, String date)
{
this.movies = movies;
this.date = date;
}
public String getDate()
{
return date;
}
public void setDate(String date)
{
this.date = date;
}
public ArrayList<String> getMovies()
{
return movies;
}
}
Here is the readFile class
package Read;
import java.util.List;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class readFile
{
public static List<movie> movies;
public static String realPath;
public static ArrayList<String> mov;
public static String j;
public static String i;
public static void main(String[]args)
{
//movies = new ArrayList<movie>();
realPath = "movie_release_dates.txt";
File f = new File(realPath);
try
{
String regex1 = "[^(0-9).+]";
String regex2 = "[^0-9$]";
Scanner sc = new Scanner(f);
while (sc.hasNextLine())
{
System.out.println("Hello");
//movies
if(!sc.nextLine().matches(regex2))
{
i = sc.nextLine();
System.out.println("Hello2");
System.out.println(i);
}
//date
while(sc.nextLine().matches(regex1))
{
System.out.println("Hello3");
if(!sc.nextLine().matches(regex1))
{
j = sc.nextLine();
mov.add(sc.nextLine());
System.out.println("Hello4");
}
}
movie movie = new movie(mov,i);
movies.add(movie);
}
// sc.close();
}
catch(Exception e)
{
System.out.println("CANT");
}
}
}
You shouldn't be calling sc.nextLine () in every check. Every NextLine () call reads next line.This means that you are checking one line and processing next line
package com.stackoverflow.q26269799;
import java.util.List;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class ReadFile {
public static List<Movie> movies = new ArrayList<Movie>();
public static String realPath;
public static ArrayList<String> mov;
public static String j;
public static String i;
public static void main(String[] args) {
//movies = new ArrayList<movie>();
realPath = "movie_release_dates.txt";
File f = new File(realPath);
if ( !f.exists()) {
System.err.println("file path not specified");
}
try {
String regex1 = "[^(0-9).+]";
String regex2 = "[^0-9$]";
Scanner sc = new Scanner(f);
while (sc.hasNextLine()) {
System.out.println("Hello");
// movies
String nextLine = sc.nextLine();
if (nextLine != null) {
if ( !nextLine.matches(regex2)) {
i = nextLine;
System.out.println("Hello2");
System.out.println(i);
}
// date
while (nextLine != null && nextLine.matches(regex1)) {
System.out.println("Hello3");
if ( !nextLine.matches(regex1)) {
j = nextLine;
mov.add(nextLine);
System.out.println("Hello4");
}
nextLine = sc.nextLine();
}
}
Movie movie = new Movie(mov, i);
movies.add(movie);
}
// sc.close();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
This is needed: //movies = new ArrayList<movie>();
Every time you call nextLine it will move the scanner point to the next line. So call it once a time and check if it match those regex. String nextLine = sc.nextLine();
Please check you whether the file path is specified.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
public class ReadFile
{
Map<String, String> movies;
public static void main(String[] args) throws IOException
{
ReadFile readFile = new ReadFile();
readFile.movies = new TreeMap<>();
try
{
readFile.importData();
printf(readFile.queryData("Der Anstandige"));
printf(readFile.queryData("Bitter"));
printf(readFile.queryData("blah"));
printf(readFile.queryData("the"));
}
catch(IOException e)
{
throw(e);
}
}
void importData() throws IOException, FileNotFoundException
{
LineNumberReader reader = null;
File file = new File("c:/movie_release_dates.txt");
try
{
reader = new LineNumberReader(new FileReader(file), 1024*64); //
String line;
String date = null, movie = null;
while((line = reader.readLine()) != null)
{
line = line.trim();
if(line.equals("")) continue;
if(line.matches(PATTERN_DATE))
{
date = line;
date = strf("%s/%s",
date.substring(date.length() - 4),
date.substring(0, date.length() - 5));
continue;
}
else
{
movie = line.trim();
}
movies.put(movie, date);
}
}
catch(FileNotFoundException e)
{
throw(e);
}
finally
{
reader.close();
}
}
String queryData(String title)
{
String regex = "(?i)" + title.replaceAll("\\s", "\\s+");
String[] matches = new String[movies.size()];
int i = 0; for(Entry<String , String> movie : movies.entrySet())
{
String key = movie.getKey();
String val = movie.getValue();
if(key.matches(regex))
{
matches[i++] = strf("{movie=%s, date=%s}", key, val);
}
else if(key.toUpperCase().trim()
.contains(title.toUpperCase().trim()))
{
matches[i++] = strf("{movie=%s, date=%s}", key, val);
}
}
String string = "";
if(matches[0] == null)
{
string = "Not found\n";
}
else
{
i = 0; while(matches[i] != null)
{
string += matches[i++] + "\n";
}
}
return string;
}
final String strf(String arg0, Object ... arg1)
{
return String.format(arg0, arg1);
}
final static void printf(String format, Object ... args)
{
System.out.printf(format, args);
}
final static void println(String x)
{
System.out.println(x);
}
final String PATTERN_DATE = "\\d{1,2}\\/\\d{1,2}\\/\\d{4}";
}
Console output:
{movie=Der Anstandige, date=2014/10/1}
{movie=Bitter Honey, date=2014/10/3}
Not found
{movie=The Good Lie, date=2014/10/3}
{movie=The Hero of Color City, date=2014/10/3}
{movie=The Supreme Price, date=2014/10/3}

Categories