Cannnot find "Array Out of Bounds Exception" Java - java

I am creating a search engine that reads in a text file, and prints out a word that a user can search for. I'm currently creating an index of arrays to be searched for. More information can be found here: http://cis-linux1.temple.edu/~yates/cis1068/sp12/homeworks/concordance/concordance.html
When I run this program right now, I get an "Array Index Out of Bounds Exception"
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 43
at SearchEngine.main(SearchEngine.java:128)
Can anyone help debug?
import java.util.*;
import java.io.*;
public class SearchEngine {
public static int getNumberOfWords (File f) throws FileNotFoundException {
int numWords = 0;
Scanner scan = new Scanner(f);
while (scan.hasNext()) {
numWords++;
scan.next();
}
scan.close();
return numWords;
}
public static void readInWords (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNext() && i<x.length) {
x[i] = scan.next();
i++;
}
scan.close();
}
public static int getNumOfDistinctWords (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int count = 0;
int i = 1;
while (scan.hasNext() && i<x.length) {
if (!x[i].equals(x[i-1])) {
count++;
}
i++;
}
scan.close();
return count;
}
public static void readInDistinctWords (String [] x, String [] y) {
int i = 1;
int k = 0;
while (i<x.length) {
if (!x[i].equals(x[i-1])) {
y[k] = x[i];
k++;
}
i++;
}
}
public static int getNumberOfLines (File input) throws FileNotFoundException {
int numLines = 0;
Scanner scan = new Scanner(input);
while (scan.hasNextLine()) {
numLines++;
scan.nextLine();
}
scan.close();
return numLines;
}
public static void readInLines (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNextLine() && i<x.length) {
x[i] = scan.nextLine();
i++;
}
scan.close();
}
Main
public static void main(String [] args) {
try {
//gets file name
System.out.println("Enter the name of the text file you wish to search");
Scanner kb = new Scanner(System.in);
String fileName = kb.nextLine();
String TXT = ".txt";
if (!fileName.endsWith(TXT)) {
fileName = fileName.concat(TXT);
}
File input = new File(fileName);
//First part of creating index
System.out.println("Creating vocabArray");
int NUM_WORDS = getNumberOfWords(input);
//System.out.println(NUM_WORDS);
String [] wordArray = new String[NUM_WORDS];
readInWords(input, wordArray);
Arrays.sort(wordArray);
int NUM_DISTINCT_WORDS = getNumOfDistinctWords(input, wordArray);
String [] vocabArray = new String[NUM_DISTINCT_WORDS];
readInDistinctWords(wordArray, vocabArray);
System.out.println("Finished creating vocabArray");
System.out.println("Creating concordanceArray");
int NUM_LINES = getNumberOfLines(input);
String [] concordanceArray = new String[NUM_LINES];
readInLines(input, concordanceArray);
System.out.println("Finished creating concordanceArray");
System.out.println("Creating invertedIndex");
int [][] invertedIndex = new int[NUM_DISTINCT_WORDS][10];
int [] wordCountArray = new int[NUM_DISTINCT_WORDS];
int lineNum = 0;
while (lineNum<concordanceArray.length) {
Scanner scan = new Scanner(concordanceArray[lineNum]);
while (scan.hasNext()) {
int wordPos = Arrays.binarySearch(vocabArray, scan.next());
wordCountArray[wordPos]+=1;
for(int i = 0; i < invertedIndex.length; i++) {
for(int j = 0; j < invertedIndex[i].length; i++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
} } }
}
lineNum++;
}
System.out.println("Finished creating invertedIndex");
}
catch (FileNotFoundException exception) {
System.out.println("File Not Found");
}
} //main
} //class

for(int j = 0; j < invertedIndex[i].length; i++) {
should probably be
j++
not
i++
Update after your fix.
That means that Arrays.binarySearch(vocabArray, scan.next()) is not finding the item being searched for. You cannot assume that the vocabArray has the item you are searching for. You will need to add an if(... < 0) for the binarySearch call.

Related

Reading from a file into an array of objects

I am trying to read data from a file that I need to be put into my array of objects. When I am trying to read 6 tests from a single student I am getting an error.
I get this error,
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6
at example.example.readStudentList(example.java:40)
at example.example.main(example.java:57)
how can I make it so I could read the 6 tests pers student and not get out of bounds?
public static Scanner openFile()throws IOException{
File input;
Scanner inFile ;
String fileName;
System.out.print("Enter input file name and path if necessary: ");//e://csc121//data.txt
fileName = KB.nextLine();
input = new File(fileName);
if( ! input.exists()){
System.out.println("File does not exists. Check the file and try again");
System.exit(0);
}
inFile = new Scanner(input); // Step 1 Initialize loop condition
if (! inFile.hasNext()){
System.out.println("Error. Data file has no data.\n");
System.exit(0);
}
return inFile;
}
public static int readStudentList(Student[] stu)throws IOException{
int i = 0;
Scanner inFile;
String name;
String id;
float quiz;
float[] tests = new float[6];
inFile = openFile();
while(inFile.hasNext()){
name = inFile.nextLine();
id = inFile.next();
for(int j = 0; i < 6; j++){
tests[j] = inFile.nextFloat();
}
quiz = inFile.nextFloat();
inFile.nextLine();
stu[i] = new Student(name, id,tests,quiz);
i++;
}
return i;
}
public static void main(String[] args)throws IOException {
Student[] arr = new Student[50];
int size;
size = readStudentList(arr);
System.out.println(size);
System.out.println(arr[0].name);
System.out.println(arr[0].id);
}
}
class Student {
public String id;
public String name;
public float[] tests = new float[6];
public float quiz;
Student(String name, String id, float[] tests, float quiz)
{
this.id = id;
this.name = name;
this.tests = tests;
this.quiz = quiz;
}
}
Take a close look at your for loop:
for(int j = 0; i < 6; j++){
Notice you are incrementing j, but checking the value of i
You have used i in your if statement instead of j. Try the following:
public static int readStudentList(Student[] stu)throws IOException {
int i = 0;
Scanner inFile;
String name;
String id;
float quiz;
float[] tests = new float[6];
inFile = openFile();
while(inFile.hasNext()){
name = inFile.nextLine();
id = inFile.next();
for(int j = 0; j < 6; j++){
tests[j] = inFile.nextFloat();
}
quiz = inFile.nextFloat();
inFile.nextLine();
stu[i] = new Student(name, id,tests,quiz);
i++;
}
return i;
}

"Cannot read the array length because "contents" is null" in word unscrambler

I'm trying to program a word unscrambler in java, but I keep getting this error Cannot read the array length because "contents" is null. I tried to use java.io.File, but it also gave me the same error when I tried it.
public static void main(String[] args) throws FileNotFoundException {
String[] contents = txtToString("allwords.txt");
Scanner in = new Scanner(System.in);
System.out.println("Insert your letters");
String input = in.nextLine();
char[] inputArray = input.toCharArray();
for(int i = 0; i < contents.length; i++)
{
for(int j = 0; j < contents[i].length()-1; j++)
{
char[] word = contents[i].toCharArray();
for(int c = 0; c < word.length-1; c++)
{
while(c<inputArray.length)
{
if(word[c]==inputArray[c])
{
word[j]=' ';
for(int s = 0; s < word.length-1;s++)
{
if(word[s]!= ' ')
{
break;
}
else
{
System.out.println("The word is "+contents[i]);
break;
}
}
}
}
}
}
}
}
private static String[] txtToString(String file) {
int count = 0;
try {
Scanner g = new Scanner(new File (file));
while(g.hasNextLine()) {
count++;
}
String[] textToArray = new String[count];
Scanner helloReader = new Scanner(new File(file));
for(int z = 0; z < count; z++) {
textToArray[z] = helloReader.next();
}
return textToArray;
}
catch (FileNotFoundException e){
}
return null;
}
Why am I getting this error?

How to take array size and elements' inputs from a text file in java?

This is for an online judge (Codeforces). Input file is like this
input.txt
6
4 3 2 1 5 6
First line is the array size and second line contains the array elements.
I've tried it by using this
public static int readFiles(String file){
try{
File f = new File(file);
Scanner Sc = new Scanner(f);
int n = Sc.nextInt();
return n;
}
catch(Exception e){
return 0;
}
}
public static int[] readFiles(String file,int n){
try{
File f = new File(file);
Scanner Sc = new Scanner(f);
Sc.nextInt();
int arr [] = new int [n];
for(int count = 0;count < n; count++){
arr[count] = Sc.nextInt();
}
return arr;
}
catch(Exception e){
return null;
}
}
public static void main (String args [] ){
int n = readFiles("input.txt");
int arr [] = readFiles("input.txt",n);
You could call the method that builds the array without provide n:
public static void main (String args [] ){
int arr [] = readFiles("input.txt");
System.out.println(Arrays.toString(arr));
int n = arr.length;
System.out.println("n is: " + n);
}
public static int[] readFiles(String file){
try{
File f = new File(file);
Scanner Sc = new Scanner(f);
int n= Sc.nextInt();
int arr [] = new int [n];
for(int count = 0;count < n; count++){
arr[count] = Sc.nextInt();
}
return arr;
}
catch(Exception e){
System.out.println("The exception is: " + e);
e.printStackTrace();
return null;
}
}
if you need n, you can get it by this line arr.length.
your code will never work because is not even compiling
if this method readFiles(String file) return an int then it makes no sense doing this
int arr [] = readFiles("input.txt",n);
hint:
read the file line by line,
check if spaces are there
get the numbers as string
parse those into integers
put them in the array
return at the end that array.
You could add a bufferedreader to read the lines one at a time, like this.
public static void main(String[] args) {
int[] numberArray = readFile();
}
public static int[] readFile(){
try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
int arraySize = Integer.parseInt(br.readLine());
String[] arrayContent = br.readLine().split(" ");
int[] newArray = new int[arraySize];
for(int i = 0; i<arraySize; i++){
newArray[i] = Integer.parseInt(arrayContent[i]);
}
return newArray;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Why don't you try this on your for loop to split the numbers between empty spaces and store it in an array :
int temp[] = Scanner.readLine().split(" ");

Java BufferedInputStream not reading the file

Need your help guys.The problem I have is in my code.While I am using RandomAccessFile I don't have any problem in writing or reading the file.But if I am trying to use ObjectInputStream with BufferedInputStream the file can't be read fully(only the first Object).
Here is my code of 2 different ways of reading and writing through stream or RandomAccessFile
public static final String FNAME1 = "1.dat";
public static final String FNAME2 = "2.dat";
final static int ID_SIZE = 10;
final static int NAME_SIZE = 20;
final static int GRADE_SIZE = 5;
final static int RECORD_SIZE = (ID_SIZE + NAME_SIZE + GRADE_SIZE) * 2; // *2 because of the UNI-CODE.
private static Scanner s = new Scanner(System.in);
public static void main(String[] args){
int studNum;
System.out.println("Please enter how many students: ");
studNum=s.nextInt();
Student<?>[] a = new Student[studNum];
try{
createArrary(a,studNum);
save(a,FNAME1);
System.out.println("2.dat saved successfully!! \n");
fileCopy(FNAME1,FNAME2);
System.out.println("The Students in file: ");
read(FNAME2);
bubbleSort(FNAME1);
fileCopy(FNAME1,FNAME2);
System.out.println("2.dat after sorting:");
read(FNAME2);
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**Creates array of Students.*/
public static Student<?>[] createArrary(Student<?>[] a,int studNum) {
String input="";
for(int i = 0; i < studNum; i++) {
System.out.println("Student # "+(i+1)+":");
System.out.print("\nPlease enter the student's id: ");
int id = s.nextInt();
System.out.print("\nPlease enter Student's name : ");
s.nextLine();
String name = s.nextLine();
System.out.print("\nPlease enter Student's grade ");
input=s.nextLine();
if(isInteger(input)){
a[i]=new Student<>(id, name,Integer.parseInt(input));
}else{
a[i]=new Student<>(id,name,input);
}
}
return a;
}
/**Check if string has integer num.*/
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
return true;
}
/**Save Student array to the file.*/
public static void save(Student<?>[] a,String fileName) throws FileNotFoundException, IOException {
try (RandomAccessFile f = new RandomAccessFile(fileName, "rw")) {
f.setLength(0);
for (Student<?> p : a) {
writeFixedLengthString(String.valueOf(p.getId()),ID_SIZE,f);
writeFixedLengthString(p.getFullName(),NAME_SIZE,f);
writeFixedLengthString(String.valueOf(p.getGrade()),GRADE_SIZE,f);
}
}
}
public static void save(Student<?>[] a,String fileName) throws FileNotFoundException, IOException {
try(ObjectOutputStream o = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)))){
for(Student<?> p : a){
writeFixedLengthString(String.valueOf(p.getId()),ID_SIZE,o);
writeFixedLengthString(p.getFullName(),NAME_SIZE,o);
writeFixedLengthString(String.valueOf(p.getGrade()),GRADE_SIZE,o);
}
}
}
/**Read Students from file.*/
public static void read(String fileName) throws FileNotFoundException, IOException,NumberFormatException {
try (RandomAccessFile f = new RandomAccessFile(fileName, "r")) {
while (f.getFilePointer() < f.length()) {
int id=Integer.parseInt(readFixedLengthString(ID_SIZE,f));
String name=readFixedLengthString(NAME_SIZE,f);
String grade=readFixedLengthString(GRADE_SIZE,f);
System.out.println(new Student<>(id, name,grade));
}
}
}
public static void read(String fileName) throws FileNotFoundException, IOException,NumberFormatException {
BufferedInputStream f;
try(ObjectInputStream i = new ObjectInputStream(f = new BufferedInputStream(new FileInputStream(fileName)))){
while (f.available() > 0) {
int id=Integer.parseInt((readFixedLengthString(ID_SIZE,i)));
String name=readFixedLengthString(NAME_SIZE,i);
String grade=readFixedLengthString(GRADE_SIZE,i);
System.out.println(new Student<>(id, name,grade));
}
}
}
/** Write fixed number of characters to a DataOutput stream */
public static void writeFixedLengthString(String s, int size,
DataOutput out) throws IOException
{ char[] chars = new char[size];
s.getChars(0, Math.min(s.length(), size), chars, 0);
for (int i = s.length(); i < size; i++)
chars[i] = ' ';
out.writeChars(new String(chars));
}
/** Read fixed number of characters from a DataInput stream */
public static String readFixedLengthString(int size, DataInput in)
throws IOException
{ char[] chars = new char[size];
for (int i = 0; i < size; i++)
chars[i] = in.readChar();
return new String(chars).replaceAll(" ", "");
}
/** Copying source file to destination file */
public static void fileCopy(String fileSource,String fileDest) throws FileNotFoundException,IOException{
try(BufferedInputStream input=new BufferedInputStream(new FileInputStream(fileSource));BufferedOutputStream output =new BufferedOutputStream(new FileOutputStream(fileDest));){
int r;
while ((r = input.read()) != -1)
{ output.write(r);
}
}
}
/** Read Students from file and returns Object */
public static <T> Student<?> readSort(RandomAccessFile f) throws FileNotFoundException, IOException,NumberFormatException {
int id=Integer.parseInt(readFixedLengthString(ID_SIZE,f));
String name=readFixedLengthString(NAME_SIZE,f);
String grade=readFixedLengthString(GRADE_SIZE,f);
return new Student<>(id, name,grade);
}
/** Receive Student Objects and Save them to file */
public static <T> void saveSort(Student<T> stud,RandomAccessFile f) throws FileNotFoundException, IOException {
writeFixedLengthString(String.valueOf(stud.getId()),ID_SIZE,f);
writeFixedLengthString(stud.getFullName(),NAME_SIZE,f);
writeFixedLengthString(String.valueOf(stud.getGrade()),GRADE_SIZE,f);
}
/** Bubble Sort of Student's grades */
#SuppressWarnings("unchecked")
public static <T> void bubbleSort(String file) throws FileNotFoundException, IOException {
try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
boolean needNextPass = true;
for (int k = 1; k < raf.length() / RECORD_SIZE && needNextPass; k++) {
needNextPass = false;
for (int i = 0; i < (raf.length() / RECORD_SIZE) - k; i++) {
raf.seek(RECORD_SIZE * i);
long tmpPrev = raf.getFilePointer();
Student<T> prevStud = (Student<T>) readSort(raf);
long tmpNext = raf.getFilePointer();
Student<T> nextStud = (Student<T>) readSort(raf);
if(isInteger((String) prevStud.getGrade())&&isInteger((String) nextStud.getGrade())){
if(Integer.parseInt((String) prevStud.getGrade())>Integer.parseInt((String) nextStud.getGrade())){
Student<T> temp=prevStud;
prevStud = nextStud;
nextStud = temp;
raf.seek(tmpPrev);
saveSort(prevStud, raf);
raf.seek(tmpNext);
saveSort(nextStud, raf);
needNextPass = true;
}
}else if(String.valueOf(prevStud.getGrade())
.compareTo(String.valueOf(nextStud.getGrade())) > 0 &&!isInteger((String) prevStud.getGrade())&&!isInteger((String) nextStud.getGrade())){
Student<T> temp=prevStud;
prevStud = nextStud;
nextStud = temp;
raf.seek(tmpPrev);
saveSort(prevStud, raf);
raf.seek(tmpNext);
saveSort(nextStud, raf);
needNextPass = true;
}else if(isInteger((String) prevStud.getGrade())&&!isInteger((String) nextStud.getGrade())||!isInteger((String) prevStud.getGrade())&&isInteger((String) nextStud.getGrade())&&String.valueOf(prevStud.getGrade())
.compareTo(String.valueOf(nextStud.getGrade())) < 0){
Student<T> temp=prevStud;
prevStud = nextStud;
nextStud = temp;
raf.seek(tmpPrev);
saveSort(prevStud, raf);
raf.seek(tmpNext);
saveSort(nextStud, raf);
needNextPass = true;
}
}
}
}
}
}
ok I understand I can just write like this.
public static void read(String fileName) throws FileNotFoundException, IOException,NumberFormatException {
try(ObjectInputStream i = new ObjectInputStream(new BufferedInputStream(new FileInputStream(fileName)))){
while (i.available()>0) {
int id=Integer.parseInt((readFixedLengthString(ID_SIZE,i)));
String name=readFixedLengthString(NAME_SIZE,i);
String grade=readFixedLengthString(GRADE_SIZE,i);
System.out.println(new Student<>(id, name,grade));
}
}
}
But how I can translate inputstream to RandomAccessFile ?

Getting file input from two source files

I am trying to write a program that merges two arrays from numbers that are in two different text files into a third array.
I have the method done to merge the two arrays into the third array.
But I don't know how to get the numbers from the second file.
Here is my current code :
public static void main(String[] args) {
int[] mergedArray = {};
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of your first file (including file extension): ");
String filename = input.next();
int[] firstArray;
try (Scanner in = new Scanner(new File(filename)))
{
int count = in.nextInt();
firstArray = new int[count];
firstArray[0] = count;
for (int i = 0; in.hasNextInt() && count != -1 && i < count; i++) {
firstArray[i] = in.nextInt();
}
} catch (final FileNotFoundException e) {
System.out.println("That file was not found. Program terminating...");
e.printStackTrace();
}
}
Any help would be appreciated thanks.
If i understood correctly, you just have to create a new Scanner, one for each file.
Like that:
public static void main(String[] args) {
int[] mergedArray = {};
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of your first file (including file extension): ");
String filename1 = input.next();
System.out.println("Enter the name of your second file (including file extension): ");
String filename2 = input.next();
int[] firstArray = null;
int[] secondArray = null;
try {
Scanner in = new Scanner(new File(filename1));
int count = in.nextInt();
firstArray = new int[count];
firstArray[0] = count;
for (int i = 0; in.hasNextInt() && count != -1 && i < count; i++) {
firstArray[i] = in.nextInt();
}
} catch (final FileNotFoundException e) {
System.out.println("That file was not found. Program terminating...");
e.printStackTrace();
}
try {
Scanner in2 = new Scanner(new File(filename2));
int count = in2.nextInt();
secondArray = new int[count];
secondArray[0] = count;
for (int i = 0; in2.hasNextInt() && count != -1 && i < count; i++) {
secondArray[i] = in2.nextInt();
}
} catch (final FileNotFoundException e) {
System.out.println("That file was not found. Program terminating...");
e.printStackTrace();
}
// do the merge operation with the 2 arrays
}
Try this
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.util.Scanner;
import static java.lang.System.*;
import java.util.Collection;
import java.util.Collections;
import java.util.ArrayList;
import java.util.Arrays;
public final class TwoSourceMergeOne{
public static void main(String[] args) {
Integer [] mergedArray = null;
try(Scanner console = new Scanner(in)){
out.println("Enter the Source file names (including file extensions) : ");
out.print(">> ");
String sourceX = console.next();
out.print("\n>> ");
String sourceY = console.next();
Path sourceXPath = Paths.get(sourceX);
Path sourceYPath = Paths.get(sourceY);
if(!Files.exists(sourceXPath,LinkOption.NOFOLLOW_LINKS) || !Files.exists(sourceXPath,LinkOption.NOFOLLOW_LINKS)){
out.println("Sorry. Some source files are missing. Please make sure that they are available !");
return;
}
Scanner xInput = new Scanner(new FileInputStream(sourceXPath.toFile()));
Scanner yInput = new Scanner(new FileInputStream(sourceYPath.toFile()));
Collection<Integer> sourceXData = new ArrayList<>();
Collection<Integer> sourceYData = new ArrayList<>();
while(xInput.hasNextInt()) sourceXData.add(xInput.nextInt());
while(yInput.hasNextInt()) sourceYData.add(yInput.nextInt());
if(!sourceXData.isEmpty() && !sourceYData.isEmpty()){
Integer [] soure_x_array = sourceXData.toArray(new Integer[sourceXData.size()]);
Integer [] source_y_array = sourceYData.toArray(new Integer[sourceYData.size()]);
mergedArray = new Integer[soure_x_array.length+source_y_array.length];
int index = 0;
for(int x : soure_x_array) mergedArray[index ++] = x;
for(int y : source_y_array) mergedArray[index ++] = y;
out.printf("The merged array is = %s",Arrays.toString(mergedArray));
}else{
out.println("Sorry. No input data !!!");
}
}catch(IOException cause){ cause.printStackTrace();}
}
}
The two source files should be in the same folder as the program.

Categories