2D Array File Reader - java

For my computer science class I'm making an website username/password program. I decided to use a 2D string array, and it hasn't been working out the best. I tried to make a file reader to read the logins that get written but I keep getting the ArrayIndexOutOfBoundsException error. My file reader code is below, and also included is my login input code. I am just starting Java so I have very basic programming knowledge.
private void fileReader() throws FileNotFoundException {
File inFile = new File(filePath);
try {
Scanner freader = new Scanner(inFile);
while (freader.hasNextLine()) {
for (int j = 1; j <= pass.length; j++) {
pass[j][0] = freader.nextLine();
pass[j][1] = freader.nextLine();
pass[j][2] = freader.nextLine();
}
}
freader.close();
} catch (IOException e) {
System.err.println(e);
System.exit(1);
}
Login input:
private void input() throws InterruptedException, FileNotFoundException {
for (int i = 0; i < pass.length; i ++){
System.out.println(i);
if (i == pass.length){
add();
}
c.print("Please enter the website: ");
pass[i][0] = c.readLine();
c.print("Please enter your username: ");
pass[i][1] = c.readLine();
c.print("Please enter your password: ");
pass[i][2] = c.readLine();
while (true){
c.clear();
synchronized (c) {
c.println("To continue adding logins, press C. To exit the program press ESC.");
c.println(pass[i][0] + " " + pass[i][1] + " " + pass[i][2]);
}
if (c.isKeyDown(KeyEvent.VK_C)){
break;
}
else if (c.isKeyDown(KeyEvent.VK_ESCAPE)){
fileWriter();
pass();
}
Thread.sleep(10);
}
}
}
Any help is greatly appreciated!! Thanks!

The main reason is because of this:
for (int j = 1; j <= pass.length; j++) {
pass[j][0] = freader.nextLine();
pass[j][1] = freader.nextLine();
pass[j][2] = freader.nextLine();
}
An array starts from 0. By making j = 1, you are starting on the second array in the group, you need to start with 0 and read up to but not including the array length.

Related

How to read "Vertically" from data sets such as CSV

So my issue right now is that I'm really unsure of how to read data "vertically". As an example:
A B C D E F
1 4 1 3 5 8
2 3 1 3 6 4
3 2 1 3 7 5
4 1 1 3 7 4
I have to manipulate this data in a few ways. I'm pretty fine with anything on the same line although I'm clueless as to how to compare items from the same column. One objective I am trying to achieve is to re-write this with only attributes that have more than one domain. So in this instance, C, D, and all the numbers below them should be omitted.
public void dataProcessing(){
File file = new File("insertFilePathHere");
try {
Scanner input = new Scanner(file);
//Please ignore these, they are more relevant to the actual data set
String titles = input.nextLine();
String types = input.nextLine();
int i = 0;
while (input.hasNext()){
String line = input.nextLine();
//This is refering to a line that is incomplete, they are to be removed
if (line.contains("?")){
continue;
}
//For printing what i have back into a table to check results
String[] row = line.split(" ");
for(String index : row){
System.out.printf("%10s", index);
}
System.out.println();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I'd solve the problem this way:
use a 2D Array (new XXX[][])
read/scan the file LineByLine (two for/while-loops)
write those lines into the array
and then you should be able to work with that array
It should look something like this (I'm sorry if there are any wrong Functions or Errors because I'm coding this without an IDE with SyntaxHighlighting or IntelliSense - there shouldn't be any Errors though):
char[][] arr = new char[rows][cols];
Scanner scanCol = new Scanner(file);
//if you know the #rows and #cols
for(int col = 0; x < cols; x++) {
Scanner scanRow = new Scanner(scanCol.nextLine());
for(int row = 0; y < rows; y++) {
//incase an Exception comes up
try {
char currChar = scanRow.next().charAt(row);
arr[col][row] = currChar;
} catch (Exception e) { //you could also write IndexOutOfBoundsException e
break;
}
}
}
//if you only know the #cols
for(int col = 0; x < cols; x++) {
Scanner scanRow = new Scanner(scanCol.nextLine());
int row = 0;
while(true) { //unfortunately there's no function called hasNextChar()
try {
char currChar = scanRow.next().charAt(row);
arr[col][row] = currChar;
} catch (Exception e) { //you could also write IndexOutOfBoundsException e
break;
}
row++;
}
}
//the top one but in a cleaner way if inline ifs work in while-Loops
int totalRows = 0;
for(int col = 0; x < cols; x++) {
Scanner scanRow = new Scanner(scanCol.nextLine());
int row = 0;
while(row=0?true:(row < totalRows)) {
try {
char currChar = scanRow.next().charAt(row);
arr[col][row] = currChar;
} catch (Exception e) { //you could also write IndexOutOfBoundsException e
break;
}
row++;
}
totalRows = row;
}
//if you just know the file exists ;)
while(scanCol.hasNextLine()) {
Scanner scanRow = new Scanner(scanCol.nextLine());
int row = 0;
while(true) {
try {
char currChar = scanRow.next().charAt(row);
arr[col][row] = currChar;
} catch (Exception e) { //you could also write IndexOutOfBoundsException e
break;
}
row++;
}
}
//to find out how many cols and rows there are
scanCol = new Scanner(file);
int cols = 0;
while(scan.hasNextLine()) {
cols++;
scan.nextLine();
}
scanRow = new Scanner(new Scanner(file).nextLine());
while(true) {
try {
scanRow.nextChar();
rows++;
} catch (Exception e) {
break;
}
}
Please feel free to correct me or ask questions about my solution!

Set boolean to true, but filewriter still overwrites the file, any advice?

I have created a simple program that sorts integers in an input file using different algorithms. I also use filewriter to output results to another file. Unfortunately no matter how I change my code, file gets overridden. Any advice?
Been searching for answer on google and tried changing the way I input the syntax but nothing works.
important bits:
setting the writer up
try {
FileWriter fileWriter = new FileWriter ("Sorted output.txt");
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
outputting to the file
out.println("User's own data set sorted using bubble sort.");
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println("Sorted Array looks like this:" + Arrays.toString(intArrayBubble));
out.println(timeToSort + bubbleSortIs + bubbleTime + "ms");
it works fine, however its used in a do while loop, with nested if statements, and each one overrides the other.
Rest of code in case its required - UPDATED - still not working
import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class PDD_Sorting {
public static void main (String [] pArgs)
{
//Array for a file
String[] FileOne;
FileOne = new String[0];
int optionOne = 1,
optionTwo = 2,
optionThree = 3,
secondaryOptionOne = 1,
secondaryOptionTwo = 2,
secondaryOptionThree = 3,
userSelection,
subUserSelection;
String unsortedArray = "Unsorted array is: ",
bubbleSort = "Sorted array using bubble sort: ",
selectionSort = "Sorted array using selection sort: ",
insertionSort = "Sorted array using insertion sort: ",
timeToSort = "Time needed to sort this array using ",
bubbleSortIs = "bubble sort is ",
selectionSortIs = "selection sort is ",
insertionSortIs = "insertion sort is ",
welcomeToSorter = "Welcome to the SORTER - program that can sort your txt files containing integeres in an ascending order!",
notFiles = "Integers, not files :)",
pleaseSelect = "Please select one of the following options, by enetering a number asociated with it.",
optionOneUserInput = "1. Sort your own data set - input your own set of data (integers, separated by colons, no spaces) into the Input file.",
optionTwoPredefined = "2. Use predetermind set of data to test the algorythms.",
optionThreeExit = "3. Exit the program.",
subMenuPleaseSelect = "Please select which algorythm would you like to use to sort this file.",
optionBubble = "(1) - Bubble Sort.",
optionSelection = "(2) - Selection Sort.",
optionInsertion = "(3) - Insertion Sort.",
usersDataBubble = "User's own data set sorted using bubble sort.",
sortedArrayLooks = "Sorted Array looks like this:",
msTime = "ms",
usersDataSelection = "User's own data set sorted using selection sort.",
usersDataInsertion = "User's own data set sorted using insertion sort.",
validOption = "Please enter a valid option i.e. 1,2 or 3",
lessThanZero = "If time shown in ms is 0, that means the time needed to conduct the sort is shorter than 1ms.",
fileCreated = "File created.",
terminatingProgram = "Terminating the program.",
unableToWriteFile = "Unable to write to file";
System.out.println(welcomeToSorter);
System.out.println(notFiles);
Scanner tInput = new Scanner (System.in);
try {
FileWriter fileWriter = new FileWriter ("Sorted output.txt");
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
do {
System.out.println(pleaseSelect);
System.out.println(optionOneUserInput);
System.out.println(optionTwoPredefined);
System.out.println(optionThreeExit);
// Scanner tInput = new Scanner (System.in);
userSelection = tInput.nextInt();
if (userSelection == optionOne) {
//System.out.println("Please enter a valid path for your file.");
String[] splitFile = null;
//String userFile = tInput.next();
FileOne = getAndPrepareFile(splitFile);
System.out.println(subMenuPleaseSelect);
System.out.println(optionBubble);
System.out.println(optionSelection);
System.out.println(optionInsertion);
subUserSelection = tInput.nextInt();
if (subUserSelection == secondaryOptionOne) {
int size = FileOne.length;
int [] intArrayBubble = new int [size];
for(int i=0; i<size; i++) {
intArrayBubble[i] = Integer.parseInt(FileOne[i]);
}
bubbleSort(intArrayBubble);
long bubbleTime = timeCount(intArrayBubble);
out.println(usersDataBubble);
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println(sortedArrayLooks + Arrays.toString(intArrayBubble));
out.println(timeToSort + bubbleSortIs + bubbleTime + msTime);
}
else if (subUserSelection == secondaryOptionTwo) {
int size2 = FileOne.length;
int [] intArraySelection = new int [size2];
for(int i=0; i<size2; i++) {
intArraySelection[i] = Integer.parseInt(FileOne[i]);
}
doSelectionSort(intArraySelection);
long selectionTime = timeCount(intArraySelection);
out.println(usersDataSelection);
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println(sortedArrayLooks + Arrays.toString(intArraySelection));
out.println(timeToSort + selectionSortIs + selectionTime + msTime);
}
else if (subUserSelection == secondaryOptionThree) {
int size3 = FileOne.length;
int [] intArrayInsertion = new int [size3];
for(int i=0; i<size3; i++) {
intArrayInsertion[i] = Integer.parseInt(FileOne[i]);
}
doInsertionSort(intArrayInsertion);
long insertionTime = timeCount(intArrayInsertion);
out.println(usersDataInsertion);
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println(sortedArrayLooks + Arrays.toString(intArrayInsertion));
out.println(timeToSort + insertionSortIs + insertionTime + msTime);
}
else {
System.out.println(validOption);
tInput.next();
}
}
else if (userSelection == optionTwo){
//file being prepared and loaded via function
String[] splitFilePredefined = null;
FileOne = getAndPrepareFilePredefined(splitFilePredefined);
//converting string array into int array so the method can sort it.
int size = FileOne.length;
int [] intArrayBubble = new int [size];
for(int i=0; i<size; i++) {
intArrayBubble[i] = Integer.parseInt(FileOne[i]);
}
int size2 = FileOne.length;
int [] intArraySelection = new int [size2];
for(int i=0; i<size2; i++) {
intArraySelection[i] = Integer.parseInt(FileOne[i]);
}
int size3 = FileOne.length;
int [] intArrayInsertion = new int [size3];
for(int i=0; i<size3; i++) {
intArrayInsertion[i] = Integer.parseInt(FileOne[i]);
}
//inserting pre-prepared int arrays into variables including a timecount method
int bubbleTime = timeCount(intArrayBubble);
int selectionTime = timeCount(intArraySelection);
int insertionTime = timeCount(intArrayInsertion);
//sorting array using various sorts
bubbleSort(intArrayBubble);
doSelectionSort(intArraySelection);
doInsertionSort(intArrayInsertion);
//out.println("Sorted arrray using insertion sort looks like this: " + Arrays.toString(intArrayInsertion));
out.println(timeToSort + bubbleSortIs + bubbleTime + "ms");
out.println(timeToSort + selectionSortIs + selectionTime + "ms");
out.println(timeToSort + insertionSortIs + insertionTime + "ms");
out.println(lessThanZero);
System.out.println(fileCreated);
}
else if (userSelection == optionThree){
System.out.println(terminatingProgram);
System.exit(0);
}
else {
System.out.println(validOption);
tInput.next();
}
out.flush();
out.close();
//tInput.close();
}while (userSelection != optionThree);
}
catch (Exception e)
{
System.out.println(unableToWriteFile);
tInput.next();
}
tInput.close();
}//end main
//method that fetches the file from predefined, hardcoded location and removes comas, esentially prepares the file for the next phase
private static String[] getAndPrepareFile (String[] splitFile)
{
Scanner fileIn = null;
try
{
fileIn = new Scanner(new FileInputStream("C:\\Users\\Greg\\Documents\\Programming\\PDD - Assignment 1\\Input.txt"));
String fileNew = fileIn.next();
splitFile = fileNew.split(",");
//System.err.println(Arrays.toString(splitFile)); //Arrays.toString needed to print the array correctly, otherwise it prints the address of the object
fileIn.close();
}
catch (IOException e)
{
System.out.println("File not found.");
//System.exit(0);
}
return splitFile;
}
//as above but works for predefined file, that can be generated using randomNumber.java program
private static String[] getAndPrepareFilePredefined (String[] splitFilePredefined)
{
Scanner fileIn = null;
try
{
fileIn = new Scanner(new FileInputStream("C:\\Users\\Greg\\Documents\\Programming\\PDD - Assignment 1\\Generated input.txt"));
String fileNew = fileIn.next();
splitFilePredefined = fileNew.split(",");
//System.err.println(Arrays.toString(splitFile)); //Arrays.toString needed to print the array correctly, otherwise it prints the address of the object
fileIn.close();
}
catch (IOException e)
{
System.out.println("File not found.");
//System.exit(0);
}
return splitFilePredefined;
}
//method used to sort a file using bubble sort
private static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(arr[j-1] > arr[j]){
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
//method used to sort a file using selection sort
private static int[] doSelectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j] < arr[index])
index = j;
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
return arr;
}
//method used to sort a file using sinsertion sort
private static int[] doInsertionSort(int[] input){
int temp;
for (int i = 1; i < input.length; i++) {
for(int j = i ; j > 0 ; j--){
if(input[j] < input[j-1]){
temp = input[j];
input[j] = input[j-1];
input[j-1] = temp;
}
}
}
return input;
}
//method used to calculate how much time has lapsed while using any of the given sort methods, outputs in ms, if less than 1 ms, outputs 0ms
private static int timeCount (int[] anArray)
{
long start = System.nanoTime();
Arrays.sort(anArray);
long end = System.nanoTime();
long timeInMillis = TimeUnit.MILLISECONDS.convert(end - start, TimeUnit.NANOSECONDS);
//System.out.println("Time spend in ms: " + timeInMillis);
return (int) timeInMillis;
}
}//end class
File gets constantly overridden, how do i stop this and make it add to file instead?
You don't need the first FileWriter fileWriter = new FileWriter("Sorted output.txt");; this is actually creating/overwriting the file, after which your PrintWriter opens it again for appending.
So, just change
// ... omitting beginning
try {
FileWriter fileWriter = new FileWriter ("Sorted output.txt");
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
do {
// ... omitting rest
to
// ... omitting beginning
try {
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
do {
// ... omitting rest
Move out.close() outside the loop
else {
System.out.println("Please enter a valid option i.e. 1,2 or 3");
tInput.next();
}
out.flush();
/* THIS -> out.close(); <- THIS */
//tInput.close();
}while (userSelection != optionThree);
out.close();
}
I tried your code and your problem is not that the file is being overwritten, but that you are closing the outputstream in the first iteration.

Java ArrayIndexOutOfBoundsException keeps appearing while trying to find most occuring word in file

I am currently building a program which reads a file and prints the most occurring words and how many times each word appears like so:
package WordLookUp;
import java.util.*;
import java.io.*;
import java.lang.*;
public class WordLookUp {
private String[] mostWords;
private Scanner reader;
private String line;
private FileReader fr;
private BufferedReader br;
private List<String> original;
private String token = " ";
public WordLookUp(String file) throws Exception {
this.reader = new Scanner(new File(file));
this.original = new ArrayList<String>();
while (this.reader.hasNext()) { //reads file and stores it in string
this.token = this.reader.next();
this.original.add(token); //adds it to my arrayList
}
}
public void findMostOccurringWords() {
List<String> mostOccur = new ArrayList<String>();
List<Integer> count = new ArrayList<Integer>();
int counter = 0;
this.mostWords = this.token.split(" "); //storing read lines in mostWords arrayList
try {
for (int i = 0; i < original.size(); i++) {
if (this.original.equals(this.mostWords[i])) {
counter++; //increase counter
mostOccur.add(this.mostWords[i]);
count.add(counter);
}
}
for (int i = 0; i < mostOccur.size(); i++) {
System.out.println("Word: " + mostOccur.get(i) + " count: " + count.get(i));
}
} catch (ArrayIndexOutOfBoundsException ae) {
System.out.println("Illegal index");
}
}
}
package WordLookUp;
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
WordLookUp wL = new WordLookUp("tiny1.txt");
wL.findMostOccurringWords();
}
}
So when I keep running my file, it throws the exception I gave it: "Illegal index". I think it is my findMostOccuringWords method. To me the logic feels correct, but I don't know why it is throwing an ArrayIndexOutOfBoundsException. I tried playing with the for loops and tried to go from int i = 0 to i < mostOccur.size() - 1 but that is not working either. Is my logic wrong ? I am not allowed to use a hashmap and our professor gave us a hint that we can do this assignment easily with arrays and ArrayLists (no other built in functions, but regexes is highly recommended for use as well for the rest of the assignment). I put a private FileReader and BufferedReader up there as I am trying to see if they would work better or not. Thanks for the advice!
Can you try to use the following codes? I think your current algorithm is wrong.
public class WordLookUp {
private List<String> original;
private List<String> mostOccur = new ArrayList<String>();
private List<Integer> count = new ArrayList<Integer>();
public WordLookUp(String file) throws Exception {
try(Scanner reader = new Scanner(new File(file));){
this.original = new ArrayList<String>();
String token = " ";
while (reader.hasNext()) { //reads file and stores it in string
token = reader.next();
this.original.add(token); //adds it to my arrayList
findMostOccurringWords(token);
}
}
}
public void findMostOccurringWords(String token) {
int counter = 0;
String[] mostWords = token.split(" "); //storing read lines in mostWords arrayList
try {
for (int i = 0; i < mostWords.length; i++) {
for(int j = 0; j < this.original.size(); j++) {
if (original.get(j).equals(mostWords[i])) {
counter++; //increase counter
}
}
if (mostOccur.contains(mostWords[i])) {
count.set(mostOccur.indexOf(mostWords[i]),counter);
}else {
mostOccur.add(mostWords[i]);
count.add(counter);
}
}
} catch (ArrayIndexOutOfBoundsException ae) {
System.out.println("Illegal index");
}
}
public void count() {
for (int i = 0; i < mostOccur.size(); i++) {
System.out.println("Word: " + mostOccur.get(i) + " count: " + count.get(i));
}
}
}
public class Main {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
WordLookUp wL = new WordLookUp("F:\\gc.log");
wL.count();
}
}
Here in this loop:
for (int i = 0; i < mostOccur.size(); i++) {
System.out.println("Word: " + mostOccur.get(i) + " count: " + count.get(i));
}
You check to make sure that i is within bounds for mostOccur but not count. I would add a condition to check to make sure it is in bounds. Such as:
for (int i = 0; i < mostOccur.size() && i < count.size(); i++) {
System.out.println("Word: " + mostOccur.get(i) + " count: " + count.get(i));
}

Only outputting last line of loop

import java.io.*;
import java.util.Random;
public class LargeDataset {
public static void main(String[] args) throws Exception {
File file = new File("src/Salary.txt");
if (file.exists()) {
System.out.print("Sorry this file already exists.");
System.exit(0);
}
String firstName = "";
String lastName = "";
String rank = "";
double salaryRange = 0.0;
for (int i = 1; i <= 1000; i++) {
try (PrintWriter output = new PrintWriter(file))
{
firstName = "FirstName" + i;
lastName = "LastName" + i;
rank = generateRandomRank();
if (rank == "assistant")
salaryRange = generateSalary(50000.00, 80000.00);
else if (rank == "associate")
salaryRange = generateSalary(60000.00, 110000.00);
else
salaryRange = generateSalary(75000.00, 130000.00);
output.printf("%s %s %s $%.2f", firstName, lastName, rank, salaryRange);
output.println();
}
}
}
public static String generateRandomRank() {
String[] rank = {"assistant", "associate", "full"};
Random random1 = new Random();
return rank[random1.nextInt(3)];
}
public static double generateSalary(double minSalary, double maxSalary) {
double randomSalary = minSalary + Math.random() * (maxSalary - minSalary);
return randomSalary;
}
}
Hi everyone. I have a program that generates 1000 lines of text and saves it into a file named Salary. The format of each line is: firstNamei, lastNamei, a random rank, and a random salary that is suited to the rank. However when I run this program it only outputs the 1000th line of the loop. I noticed however, when I don't put the PrintWriter in the try statement and close it after the loop by myself, it runs fine and generates all 1000 lines. Why is it only generating the last line based on how it is right now though?
You should open your PrintWriter once, and then write to it many times from your loop, not the other way around:
try (PrintWriter output = new PrintWriter(file)) {
for (int i = 1; i <= 1000; i++) {
firstName = "FirstName" + i;
lastName = "LastName" + i;
rank = generateRandomRank();
if (rank == "assistant")
salaryRange = generateSalary(50000.00, 80000.00);
else if (rank == "associate")
salaryRange = generateSalary(60000.00, 110000.00);
else
salaryRange = generateSalary(75000.00, 130000.00);
output.printf("%s %s %s $%.2f", firstName, lastName, rank, salaryRange);
output.println();
}
}
You should use the above pattern instead of what you have. If you want an exact fix to your current code, then you may try opening the PrintWriter in append mode:
for (int i=1; i <= 1000; i++) {
try (PrintWriter output = new PrintWriter(new FileOutputStream(file, true)) {
// same logic
}
}
This should also work, because now, even though you create a new PrintWriter for each iteration of the loop (inefficient), you open the underlying file in append mode, so each new line should get written properly.
Every time that you are iterating through your 1000 you are creating a new file
for (int i = 1; i <= 1000; i++) {
try (PrintWriter output = new PrintWriter(file))
...
}
move it before the loop
try (PrintWriter output = new PrintWriter(file)) {
for (int i = 1; i <= 1000; i++) {
}
}

How to find similar lines in two text files irrespective of the line number at which they occur

I am trying to open two text files and find similar lines in them.
My code is correctly reading all the lines from both the text files.
I have used nested for loops to compare line1 of first text file with all lines of second text file and so on.
However, it is only detecting similar lines which have same line number,
(eg. line 1 of txt1 is cc cc cc and line 1 of txt2 is cc cc cc, then it correctly finds and prints it),
but it doesn't detect same lines on different line numbers in those files.
import java.io.*;
import java.util.*;
public class FeatureSelection500 {
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
File f1 = new File("E://implementation1/practise/ComUpdatusPS.exe.hex-04-ngrams-Freq.txt");
File f2 = new File("E://implementation1/practise/top-300features.txt");
Scanner scan1 = new Scanner(f1);
Scanner scan2 = new Scanner(f2);
int i = 1;
List<String> txtFileOne = new ArrayList<String>();
List<String> txtFileTwo = new ArrayList<String>();
while (scan1.hasNext()) {
txtFileOne.add(scan1.nextLine());
}
while (scan2.hasNext())
{
txtFileTwo.add(scan2.nextLine());
}
/*
for(String ot : txtFileTwo )
{
for (String outPut : txtFileOne)
{
// if (txtFileTwo.contains(outPut))
if(outPut.equals(ot))
{
System.out.print(i + " ");
System.out.println(outPut);
i++;
}
}
}
*/
for (int j = 0; j < txtFileTwo.size(); j++) {
String fsl = txtFileTwo.get(j);
// System.out.println(fileContentSingleLine);
for (int z = 0; z < 600; z++) // z < txtFileOne.size()
{
String s = txtFileOne.get(z);
// System.out.println(fsl+"\t \t"+ s);
if (fsl.equals(s)) {
System.out.println(fsl + "\t \t" + s);
// my line
// System.out.println(fsl);
} else {
continue;
}
}
}
}
}
I made your code look nicer, you're welcome :)
Anyway, I don't understand that you get that bug. It runs through all of the list2 for every line in the list1...
import java.io.*;
import java.util.*;
public class FeatureSelection500 {
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
File file1 = new File("E://implementation1/practise/ComUpdatusPS.exe.hex-04-ngrams-Freq.txt");
File file2 = new File("E://implementation1/practise/top-300features.txt");
Scanner scan1 = new Scanner(file1);
Scanner scan2 = new Scanner(file2);
List<String> txtFile1 = new ArrayList<String>();
List<String> txtFile2 = new ArrayList<String>();
while (scan1.hasNext()) {
txtFile1.add(scan1.nextLine());
}
while (scan2.hasNext()) {
txtFile2.add(scan2.nextLine());
}
for (int i = 0; i < txtFile2.size(); i++) {
String lineI = txtFile2.get(i);
// System.out.println(fileContentSingleLine);
for (int j = 0; j < txtFile1.size(); j++){ // z < txtFileOne.size(
String lineJ = txtFile1.get(j);
// System.out.println(fsl+"\t \t"+ s);
if (lineI.equals(lineJ)) {
System.out.println(lineI + "\t \t" + lineJ);
// my line
// System.out.println(fsl);
}
}
}
}
}
I don't see any problem with your code. Even the block you commented is absolutely fine. Since, you are doing equals() you should make sure that you have same text (same case) in the two files for them to be able to satisfy the condition successfully.
for(String ot : txtFileTwo )
{
for (String outPut : txtFileOne)
{
if(outPut.equals(ot)) /* Check Here */
{
/* Please note that here i will not give you line number,
it will just tell you the number of matches in the two files */
System.out.print(i + " ");
System.out.println(outPut);
i++;
}
}
}

Categories

Resources