Keep getting Exceptions - java

I am trying to read two files, match them, then print another file as result. But i keep getting this ArrayIndexOutOfBoundsException. I have no idea how to fix it, can someone help me please? Here is my code:
import java.io.IOException;
import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
class Test{
final static char[][] DIG_CHAR = {{}, {}, {'A', 'B', 'C'}, {'D', 'E', 'F'}, {'G', 'H', 'I'}, {'J', 'K', 'L'}, {'M', 'N', 'O'}, {'P', 'Q', 'R', 'S'}, {'T', 'U', 'V'}, {'W', 'X', 'Y', 'Z'}};
public static void main(String[] args) throws IOException {
String s1 = "telephone.txt";
String s2 = "sample.txt";
Process(s1, s2);
}
public static void Process(String s1, String s2) throws IOException {
int size43 = ThreeCharacters(s2);
int size44 = FourCharacters(s2);
int size47 = SevenCharacters(s2);
String[] WordsOf3 = Store3Words(s2, size43);
String[] WordsOf4 = Store4Words(s2, size44);
String[] WordsOf7 = Store7Words(s2, size47);
String[] s = Char2Dig(WordsOf3);
String[] p = Char2Dig(WordsOf4);
String[] q = Char2Dig(WordsOf7);
Print3(WordsOf3, s, s1);
Print4(WordsOf4, p, s1);
Print7(WordsOf7, q, s1);
}
public static int ThreeCharacters(String s2) throws IOException {
Scanner in = new Scanner(new File(s2));
int count = 0;
while (in.hasNextLine()) {
in.nextLine();
if (in.nextLine().length() == 3) {
count++;
}
}
in.close();
return count;
}
public static int FourCharacters(String s2) throws IOException {
Scanner in = new Scanner(new File(s2));
int count = 0;
while (in.hasNextLine()) {
in.nextLine();
if (in.nextLine().length() == 4) {
count++;
}
}
in.close();
return count;
}
public static int SevenCharacters(String s2) throws IOException {
Scanner in = new Scanner(new File(s2));
int count = 0;
while (in.hasNextLine()) {
in.nextLine();
if(in.nextLine().length() == 7) {
count++;
}
}
in.close();
return count;
}
public static String[] Store3Words(String s2, int size) throws IOException {
//Here is where i keep getting the ArrayIndexOutOfBoundsException, probably same as the next two methods
String[] words = new String[size];
String temp = "";
Scanner in = new Scanner(new File(s2));
int i = 0;
while (in.hasNextLine()) {
temp = in.nextLine();
if (temp.length() == 3) {
words[i] = temp;
i++;
}
}
in.close();
return words;
}
public static String[] Store4Words(String s2, int size) throws IOException {
String[] words = new String[size];
String temp = "";
Scanner in = new Scanner(new File(s2));
int i = 0;
while (in.hasNextLine()) {
temp = in.nextLine();
if (temp.length() == 4) {
words[i] = temp;
i++;
}
}
in.close();
return words;
}
public static String[] Store7Words(String s2, int size) throws IOException {
String[] words = new String[size];
String temp = "";
Scanner in = new Scanner(new File(s2));
int i = 0;
while (in.hasNextLine()) {
temp = in.nextLine();
if (temp.length() == 7) {
words[i] = temp;
i++;
}
}
in.close();
return words;
}
public static String[] Char2Dig(String[] arr) { // ||
String temp = "";
String q = "";
String str = "";
for (int i = 0; i < arr.length; i++) {
temp = arr[i];
str = "";
for (int j = 0; j < temp.length(); j++) {
for (int m = 2; m < DIG_CHAR.length; m++) {
for (int k = 0; k < DIG_CHAR[m].length; k++) {
if (temp.charAt(j) == DIG_CHAR[m][k]) {
q = q + DIG_CHAR[m];
str = str + q;
break;
}
}
if (q == "") {
continue;
}
break;
}
q = "";
}
arr[i] = str;
}
return arr;
}
public static void Print3(String[] WordsOf3, String[] arr, String s1) throws IOException {
PrintWriter outfile = new PrintWriter(new FileWriter("result.txt"));
Scanner in = new Scanner(new File(s1));
String temp = "";
while (in.hasNextLine()) {
temp = in.nextLine().substring(4, 7);
for (int i = 0; i < arr.length; i++) {
if (arr[i] == temp) {
outfile.println(temp + ": " + WordsOf3[i]);
}
}
}
outfile.close();
}
public static void Print4(String[] WordsOf4, String[] arr, String s1) throws IOException {
PrintWriter outfile = new PrintWriter(new FileWriter("result.txt"));
Scanner in = new Scanner(new File(s1));
String temp = "";
while (in.hasNextLine()) {
temp = in.nextLine().substring(7, 11);
for (int i = 0; i < arr.length; i++) {
if (arr[i] == temp) {
outfile.println(temp + ": " + WordsOf4[i]);
}
}
}
outfile.close();
}
public static void Print7(String[] WordsOf7, String[] arr, String s1) throws IOException {
PrintWriter outfile = new PrintWriter(new FileWriter("result.txt"));
Scanner in = new Scanner(new File(s1));
String temp = "";
while (in.hasNextLine()) {
temp = in.nextLine().substring(4);
for (int i = 0; i < arr.length; i++) {
if (arr[i] == temp) {
outfile.println(temp + ": " + WordsOf7[i]);
}
}
}
outfile.close();
}
}

The problem is that you do not count right. You miss the number line of 3, 4 or 7 characters. Let's look at your code, method ThreeCharacters:
public static int ThreeCharacters(String s2) throws IOException {
Scanner in = new Scanner(new File(s2));
int count = 0;
while (in.hasNextLine()) {
in.nextLine();
if (in.nextLine().length() == 3) {
count++;
}
}
in.close();
return count;
}
in.nextLine() reads and skips one line, then if (in.nextLine().length() == 3) again reads and skips another line. At the end, you check only one line over two. The suggestion is to remove the in.nextLine() that is not doing anything, I guess. And if for any reason you put it on purpose, add the same line in Store3Words so that you also process only one line over two. This will solve the ArrayIndexOutOfBoundsException, but you will possibly have other problem in your code, because as beginner, you did not follow the path you are supposed to follow in programming: write one method, test and make sure it is working and move to the next method.
Altogether, I suggest you write a single method to count and a single one to store, your code can become as compact as this:
import java.io.IOException;
import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
class TestApp{
final static char[][] DIG_CHAR = {{}, {}, {'A', 'B', 'C'}, {'D', 'E', 'F'},
{'G', 'H', 'I'}, {'J', 'K', 'L'}, {'M', 'N', 'O'}, {'P', 'Q', 'R', 'S'},
{'T', 'U', 'V'}, {'W', 'X', 'Y', 'Z'}};
public static void main(String[] args) throws IOException {
String s1 = "telephone.txt";
String s2 = "sample.txt";
Process(s1, s2);
}
public static void Process(String s1, String s2) throws IOException {
int size43 = count(s2, 3);
int size44 = count(s2, 4);
int size47 = count(s2, 7);
/////
System.out.println("lines of 3: "+size43 );
System.out.println("lines of 4: "+size44 );
System.out.println("lines of 7: "+size47 );
/////
String[] WordsOf3 = store(s2, size43, 3);
String[] WordsOf4 = store(s2, size44, 4);
String[] WordsOf7 = store(s2, size47, 7);
/////
System.out.println("lines of 3" );
for(int i = 0; i<size43; i++){
System.out.println( WordsOf3[i] );
}
System.out.println("lines of 4" );
for(int i = 0; i<size44; i++){
System.out.println( WordsOf4[i] );
}
System.out.println("lines of 7" );
for(int i = 0; i<size47; i++){
System.out.println( WordsOf7[i] );
}
/////
String[] s = Char2Dig(WordsOf3);
String[] p = Char2Dig(WordsOf4);
String[] q = Char2Dig(WordsOf7);
Print3(WordsOf3, s, s1);
Print4(WordsOf4, p, s1);
Print7(WordsOf7, q, s1);
}
/** Single method that returns the number of lines of given number of char
* With this single method, no need to write ThreeCharacters, FourCharacters
* and SevenCharacters
*/
public static int count(String fName, int nChar) throws IOException {
Scanner in = new Scanner(new File(fName));
int count = 0;
String tmp; // Note the tmp variable, so that we do not advance twice
while (in.hasNextLine()) {
if (in.nextLine().length() == nChar) {
count++;
}
}
in.close();
return count;
}
/** Single method that returns all the lines of given number of char
* With this single method, no need to write Store3Words, Store4Words
* and Store7Words
*/
public static String[] store(String fName, int size, int nChar) throws IOException {
String[] words = new String[size];
String temp = "";
Scanner in = new Scanner(new File(fName));
int i = 0;
while (in.hasNextLine()) {
temp = in.nextLine();
if (temp.length() == nChar) {
words[i] = temp;
i++;
}
}
in.close();
return words;
}
public static String[] Char2Dig(String[] arr) { // ||
String temp = "";
String q = "";
String str = "";
for (int i = 0; i < arr.length; i++) {
temp = arr[i];
str = "";
for (int j = 0; j < temp.length(); j++) {
for (int m = 2; m < DIG_CHAR.length; m++) {
for (int k = 0; k < DIG_CHAR[m].length; k++) {
if (temp.charAt(j) == DIG_CHAR[m][k]) {
q = q + DIG_CHAR[m];
str = str + q;
break;
}
}
if (q == "") {
continue;
}
break;
}
q = "";
}
arr[i] = str;
}
return arr;
}
public static void Print3(String[] WordsOf3, String[] arr, String s1) throws IOException {
PrintWriter outfile = new PrintWriter(new FileWriter("result.txt"));
Scanner in = new Scanner(new File(s1));
String temp = "";
while (in.hasNextLine()) {
temp = in.nextLine().substring(4, 7);
for (int i = 0; i < arr.length; i++) {
if (arr[i] == temp) {
outfile.println(temp + ": " + WordsOf3[i]);
}
}
}
outfile.close();
}
public static void Print4(String[] WordsOf4, String[] arr, String s1) throws IOException {
PrintWriter outfile = new PrintWriter(new FileWriter("result.txt"));
Scanner in = new Scanner(new File(s1));
String temp = "";
while (in.hasNextLine()) {
temp = in.nextLine().substring(7, 11);
for (int i = 0; i < arr.length; i++) {
if (arr[i] == temp) {
outfile.println(temp + ": " + WordsOf4[i]);
}
}
}
outfile.close();
}
public static void Print7(String[] WordsOf7, String[] arr, String s1) throws IOException {
PrintWriter outfile = new PrintWriter(new FileWriter("result.txt"));
Scanner in = new Scanner(new File(s1));
String temp = "";
while (in.hasNextLine()) {
temp = in.nextLine().substring(4);
for (int i = 0; i < arr.length; i++) {
if (arr[i] == temp) {
outfile.println(temp + ": " + WordsOf7[i]);
}
}
}
outfile.close();
}
}
If I understood the logic behind the Print3, Print4 and Print7 I would have do the same. Also notice that I added some print statement to see what is going on. That is very helpful to see if your code is doing what it is supposed to do.

Related

Subsequence words

Suppose this is my .txt file ABCDBCD and I want to use .substring to get this:
ABC BCD CDB DBC BCD
How can I achieve this? I also need to stop the program if a line is shorter than 3 characters.
static void lesFil(String fil, subsekvens allHashMapSubsequences) throws FileNotFoundException{
Scanner scanner = new Scanner(new File("File1.txt"));
String currentLine, subString;
while(scanner.hasNextLine()){
currentLine = scanner.nextLine();
currentLine = currentLine.trim();
for (int i = 0; i + subSize <= currentLine.length(); i++){
subString = currentLinje.substring(i, i + subSize);
subSekStr.putIfAbsent(subString, new subsequence(subString));
}
}
scanner.close();
With a minor changes of your code:
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("C:\\Users\\Public\\File1.txt"));
String currentLine, subString;
int subSize = 3;
while (scanner.hasNextLine()) {
currentLine = scanner.nextLine();
currentLine = currentLine.trim();
if (currentLine.length() < subSize) {
break;
}
for (int i = 0; i + subSize <= currentLine.length(); i++) {
subString = currentLine.substring(i, i + subSize);
System.out.print(subString + " ");
}
System.out.print("\n");
}
scanner.close();
}
This may be what you need
String str = "ABCDBCD";
int substringSize = 3;
String substring;
for(int i=0; i<str.length()-substringSize+1; i++){
substring = str.substring(i, i+substringSize);
System.out.println(substring);
}
import java.util.*;
public class Main
{
public static void main(String[] args) {
String input = "ABCDBCD";
for(int i = 0 ; i < input.length() ; i++) {
if(i < input.length() - 2) {
String temp = input.substring(i,i+3);
System.out.println(temp);
}
}
}
}

Manipulating strings and integers via two dimensional array from an external file java

I am trying to design a program that takes data from an external file, stores the variable to arrays and then allows for manipulation.sample input:
String1 intA1 intA2
String2 intB1 intB2
String3 intC1 intC2
String4 intD1 intD2
String5 intE1 intE2
I want to be able to take these values from the array and manipulate them as follows;
For each string I want to be able to take StringX and computing((intX1+
intX2)/)
And for each int column I want to be able to do for example (intA1 + intB1 + intC1 + intD1 + intE1)
This is what I have so far, any tips?
**please note java naming conventions have not been taught in my course yet.
public class 2D_Array {
public static void inputstream(){
File file = new File("data.txt");
try (FileInputStream fis = new FileInputStream(file)) {
int content;
while ((content = fis.read()) != -1) {
readLines("data.txt");
FivebyThree();
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static int FivebyThree() throws IOException {
Scanner sc = new Scanner(new File("data.txt"));
int[] arr = new int[10];
while(sc.hasNextLine()) {
String line[] = sc.nextLine().split("\\s");
int ele = Integer.parseInt(line[1]);
int index = Integer.parseInt(line[0]);
arr[index] = ele;
}
int sum = 0;
for(int i = 0; i<arr.length; i++) {
sum += arr[i];
System.out.print(arr[i] + "\t");
}
System.out.println("\nSum : " + sum);
return sum;
}
public static String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null)
{
lines.add(line);
}
return lines.toArray(new String[lines.size()]);
}
/* int[][] FivebyThree = new int[5][3];
int row, col;
for (row =0; row < 5; row++) {
for(col = 0; col < 3; col++) {
System.out.printf( "%7d", FivebyThree[row][col]);
}
System.out.println();*/
public static void main(String[] args)throws IOException {
inputstream();
}
}
I see that you read data.txt twice and do not use first read result at all. I do not understand, what you want to do with String, but having two-dimension array and calculate sum of columns of int is very easy:
public class Array_2D {
static final class Item {
final String str;
final int val1;
final int val2;
Item(String str, int val1, int val2) {
this.str = str;
this.val1 = val1;
this.val2 = val2;
}
}
private static List<Item> readFile(Reader reader) throws IOException {
try (BufferedReader in = new BufferedReader(reader)) {
List<Item> content = new ArrayList<>();
String str;
while ((str = in.readLine()) != null) {
String[] parts = str.split(" ");
content.add(new Item(parts[0], Integer.parseInt(parts[1]), Integer.parseInt(parts[2])));
}
return content;
}
}
private static void FivebyThree(List<Item> content) {
StringBuilder buf = new StringBuilder();
int sum1 = 0;
int sum2 = 0;
for (Item item : content) {
// TODO do what you want with item.str
sum1 += item.val1;
sum2 += item.val2;
}
System.out.println("str: " + buf);
System.out.println("sum1: " + sum1);
System.out.println("sum2: " + sum2);
}
public static void main(String[] args) throws IOException {
List<Item> content = readFile(new InputStreamReader(Array_2D.class.getResourceAsStream("data.txt")));
FivebyThree(content);
}
}

Reading a CSV in Java / Jython

Here's a simple problem:
public static double[] stringsToDoubles(String[] inputArr) {
double[] nums = new double[inputArr.length];
for (int i = 0; i < nums.length; i++) {
nums[i] = Double.parseDouble(inputArr[i]);
}
return nums;
}
public static double[][] readPointCloudFile(String filename, int n) {
double[][] points = new double[n][];
String delimiter = ",";
Scanner sc = new Scanner(filename);
for (int i = 0; i < n; i++) {
String line = sc.nextLine();
points[i] = stringsToDoubles(line.split(delimiter));
}
return points;
}
from jython I import properly, and then call the function as
readPointCloudFile("points.txt", 3)
This gives the error
java.lang.NumberFormatException: java.lang.NumberFormatException: For input string: "points.txt"
You never read from the file. You pass the file name to the Scanner and assume that this string is your csv data, but it is just the filename.
Reading a file can be done as follows when you use Java 8:
import java.nio.file.Files;
import java.nio.file.Paths;
[...]
public static double[][] readPointCloudFile(String filename, int n) {
double[][] points = new double[n][];
String delimiter = ",";
String filecontent = new String(Files.readAllBytes(Paths.get(filename)));
Scanner sc = new Scanner(filecontent);
for (int i = 0; i < n; i++) {
String line = sc.nextLine();
points[i] = stringsToDoubles(line.split(delimiter));
}
return points;
}
Here's my solution in the spirit of solving your own problems, but I'll give someone else credit because the other solutions are probably better.
public static double[] stringsToDoubles(String[] inputArr){
double[] nums = new double[inputArr.length];
for(int i = 0; i < nums.length; i++){
nums[i] = Double.parseDouble(inputArr[i]);
}
return nums;
}
public static double[][] readPointCloudFile(String filename, int n) throws FileNotFoundException{
double[][] points = new double[n][];
String delimiter = ",";
try{
Scanner sc = new Scanner(new File(filename));
for(int i = 0; i < n; i++){
String line = sc.nextLine();
points[i] = stringsToDoubles(line.split(delimiter));
}
} catch (FileNotFoundException e){
System.err.println(e.getMessage());
} finally {
return points;
}
}

match a string in file java

I have a problem. I need to use the first row of the txt as my string and then look in the same txt the occurrences and print the number, but I have a problem, for example; if my txt is like: wordwordword and my string is word, it only counts the first word, it does´t print the counter: 3, print the counter: 1. How can I solve this?
Demo.java
import java.io.*;
import java.util.*;
public class Demo {
public static void main(String args[]) throws java.io.IOException {
BufferedReader in = new BufferedReader(new FileReader("c.txt"));
Scanner sc = new Scanner(System.in);
String s1;
s1 = in.readLine();
String Word;
Word = s1;
String line = in.readLine();
int count = 0;
String s[];
do {
s = line.split(" ");
for (int i = 0; i < s.length; i++) {
String a = s[i];
if (a.contains(Word))
count++;
}
line = in.readLine();
} while (line != null);
System.out.println("first line: " + s1);
System.out.print("There are " + count + " occurences of " + Word
+ " in ");
java.io.File file = new java.io.File("c.txt");
Scanner input = new Scanner(file);
while (input.hasNext()) {
String word = input.nextLine();
System.out.print(word);
}
}
}
txt:
GAGCATAGA
CGAGAGCATATAGGAGCATATCTTGAGCATACCGAGCATATGAGCATAATATACCCGTCCGAGAGCATACACTGAGCATAAAGGAGCATAGAGCATACAACTGAGAATGGAGCATAGAGCATACGGAGCATAAGAGCATAGAGCATAGAGCATACGGAGCATAGAGCATAGAGCATAGCCGATGGGGAGCATACTGTTACGTAGAGCATACGAGCATAGCGCAAGAGCATAAAGAGCATAGAGCATATGAGCATATAGAGCATACGAGCATACAAGATCCGGGGAGCATAGCGAGGTAATAGTCGGAGCATAGAGCATAGAGCATATGAGCATACGGGAGCATAAATGAGCATAAGGAGCATAGAGCATAGAGCATAAGAGCATATCTCGAGCATAAGCGAGCATAGAGCATAAAAATCAATCACGTTGAGCATATGAGCATAAATACTGGAGCATAGATCGAGCATAGTAGAGCATACGAGCATAGAGCATAGGAGCATAAGAGCATATGAGCATATTGAGCATATGAAGGAGCATAAAAATGAGCATAAGGAGCATACCATCGTTGAGCATAATCCGAGCATAGGAGCATAGAATAGAGCATAGACAGGAGTTTTTGGAGCATATGAGCATAGAGCATAGAGCATAGAGCATAGAGCATAGAGCATAGAGCATATTCGAGCATAATTGAGCATATGAGCATAGAGCATATGGAGCATAGGCTGAGCATACCGAGCATAGCAATTAGAGCATAATCCTAGGGAGCATAGGAGCATACGTGAGCATAGCTGAGCATAGAGCATAGAGCATAGTGTTCGAGCATAGAGCATAGAGCATATGAGCATAGAGCATACTTGAGCATATGGTACGAGCATAGGAGCATATAAGGAGGAGCATATCGAGCATAGAGCATAGGCCTGGCCAGAGCATATAACCGAGCATAGGGTTGGAGCATAAGGCCGGAGCATACGAGCATACGAGCATATGAAATGAGCATAATGTGAGCATAGAGCATATCGAGCATATGAGCATAGGAGCATA
in this example with the txt, the program should print the counter= 21
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Match {
public static String TEXT_FILE_LOCATION="input.txt";
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File(TEXT_FILE_LOCATION));
String stringToSearch=in.nextLine();
StringBuffer buffer=new StringBuffer();
for(;in.hasNext();){
buffer.append(in.next());
}
Pattern pattern = Pattern.compile(stringToSearch);
Matcher matcher = pattern.matcher(buffer.toString());
int from = 0;
int count = 0;
while(matcher.find(from)) {
count++;
from = matcher.start() + 1;
}
System.out.println("Number of matches : "+count);
}
}
You can do it by looping through your text then match the string with part of the text.
Here it is:
public static void main(String[] args) {
String word = "word";
String text = "wordwordword";
int count = 0;
for(int i =0 ; i <text.length() ; i++){
for(int j = 0 ; j < word.length();j++){
if((j+i)>=text.length())break;
if(word.charAt(j)!=text.charAt(j+i))break;
if(j==word.length()-1)count++;
}
}
System.out.println(count);//prints 3
}
Also you could use .toCharArray() to get the characters in the string before looping to enhance the performance.
Here is the modified code for that :
public static void main(String[] args) {
char[] word = "word".toCharArray();
char[] text = "wordwordword".toCharArray();
int count = 0;
for(int i =0 ; i <text.length ; i++){
for(int j = 0 ; j < word.length;j++){
if((j+i)>=text.length)break;
if(word[j]!=text[j+i])break;
if(j==word.length-1)count++;
}
}
System.out.println(count);
}

Java - substring issues

I'm going to show all of my code here so you guys get a gist of what I'm doing.
import java.io.*;
import java.util.*;
public class Plagiarism {
public static void main(String[] args) {
Plagiarism myPlag = new Plagiarism();
if (args.length == 0) {
System.out.println("Error: No files input");
}
else if (args.length > 0) {
try {
List<String> foo = new ArrayList<String>();
for (int i = 0; i < 2; i++) {
BufferedReader reader = new BufferedReader (new FileReader (args[i]));
foo = simplify(reader);
for (int j = 0; j < foo.size(); j++) {
System.out.print(foo.get(j));
}
}
int blockSize = Integer.valueOf(args[2]);
System.out.println(args[2]);
// String line = foo.toString();
List<String> list = new ArrayList<String>();
for (int k = 0; k < foo.size() - blockSize; k++) {
list.add(foo.toString().substring(k, k+blockSize));
}
System.out.println(list);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public static List<String> simplify(BufferedReader input) throws IOException {
String line = null;
List<String> myList = new ArrayList<String>();
while ((line = input.readLine()) != null) {
myList.add(line.replaceAll("[^a-zA-Z]","").toLowerCase());
}
return myList;
}
}
This is the code that is using substring.
int blockSize = Integer.valueOf(args[2]);
//"foo" is an ArrayList<String> which I have to convert toString() to use substring().
String line = foo.toString();
List<String> list = new ArrayList<String>();
for (int k = 0; k < line.length() - blockSize; k++) {
list.add(line.substring(k, k+blockSize));
}
System.out.println(list);
When I specify blockSize as 4 in cmd this is the result:
[[, a, , ab, abc ]
the text file (standardised using my other code) is this:
abcdzaabcdd
so the result should be this:
[abcd, bcdz, cdza, ] etc.
Any help?
Thanks in advance.
Here is code showing how to improve a little your code. Main change is returning simplified string from simplify method instead of List<String> of simplified lines, which after converting it to string returned String in form
[value0, value1, value2, ...]
Now code returns String in form value0value1value2.
Another change is lowering indentation lever by removing unnecessary else if statement and braking control flow with System.exit(0); (you can also use return; here).
class Plagiarism {
public static void main(String[] args) throws Exception {
//you are not using 'myPlag' anywhere, you can safely remove it
// Plagiarism myPlag = new Plagiarism();
if (args.length == 0) {
System.out.println("Error: No files input");
System.exit(0);
}
String foo = null;
for (int i = 0; i < 2; i++) {
BufferedReader reader = new BufferedReader(new FileReader(args[i]));
foo = simplify(reader);
System.out.println(foo);
}
int blockSize = Integer.valueOf(args[2]);
System.out.println(args[2]);
List<String> list = new ArrayList<String>();
for (int k = 0; k < foo.length() - blockSize; k++) {
list.add(foo.toString().substring(k, k + blockSize));
}
System.out.println(list);
}
public static String simplify(BufferedReader input)
throws IOException {
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = input.readLine()) != null) {
sb.append(line.replaceAll("[^a-zA-Z]", "").toLowerCase());
}
return sb.toString();
}
}

Categories

Resources