Reading txt file in java, program skipping the first line [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
My program is skipping the first line of my .txt file. Here is where my code is supposed to read from the .txt file.
static int getPints(int[] pints) throws IOException {
Scanner inputFile = new Scanner(new File("BloodInFile.txt"));
int count = 0;
while (inputFile.hasNext()) {
pints[count] = inputFile.nextInt();
count++;
}
return pints[count];
}
It should be reading 7 integers, but I only get 6 of them to be read.
The rest of the code works, but I am not sure how to get it to read the first integer.
This is the rest of my code:
static int getPints(int[] pints) throws IOException {
Scanner inputFile = new Scanner(new File("BloodInFile.txt"));
int count = 0;
while (inputFile.hasNext()) {
pints[count] = inputFile.nextInt();
count++;
}
inputFile.close();
return pints[count];
}
static double getAverage(int pints[], int MAX_HOURS) {
int counter;
double totalPints = 1;
double averagePints;
for (counter = 1; counter < MAX_HOURS - 1; counter++) {
System.out.println("pints:" + pints[counter]);
totalPints = totalPints + pints[counter];
}
averagePints = totalPints / (MAX_HOURS - 2);
System.out.println("Total pints: " + totalPints);
return averagePints;
}
static double getHigh(int pints[], int MAX_HOURS) {
int index = 1;
double highest = pints[index];
for (index = 1; index < MAX_HOURS - 1; index++) {
if (pints[index] > highest) {
highest = pints[index];
}
}
return highest;
}
static double getLow(int pints[], int MAX_HOURS) {
int index = 1;
double lowest = pints[index];
for (index = 1; index < MAX_HOURS - 1; index++) {
if (pints[index] < lowest) {
lowest = pints[index];
}
}
return lowest;
}

I did it once just like this, maybe that works for you too
public static List<String> get16TeamsFromTxt() throws IOException {
Path currentRelativePath = Paths.get("");
String s1 = currentRelativePath.toAbsolutePath().normalize().toString();
Scanner s = new Scanner(new File(s1+"/16.txt"));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNextLine()){
list.add(s.nextLine());
}
s.close();
return list;
}
This way you should get the list with all of your numbers. Mine is with string, but should work with int.

Related

Alternative way to get the string input from the user [duplicate]

This question already has answers here:
Why does input.nextint method have a \n as a leftover?
(2 answers)
What does java.lang.ArrayIndexOutOfBoundsException mean? [duplicate]
(7 answers)
Closed 2 years ago.
I have implemented the following code which takes these values as input:-
3 6
CLICK 1
CLICK 2
CLICK 3
CLICK 2
CLOSEALL
CLICK 1
But for taking string input I tried nextLine() but it is not taking input in that case.If I use next() then it treats CLICK and 1 as two different strings and so I am getting ArrayIndexOutOfBoundsException as I am splitting the string and parsing it to int. What is the alternative to handling such inputs?
import java.util.*;
public class TweetClose {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int open = 0;
int a[] = new int[50];
for (int i = 1; i <= n; i++) {
a[i] = 0;
}
for (int i = 0; i < k; i++) {
String s = sc.nextLine();
if (s.equals("CLOSEALL")) {
open = 0;
for (int j = 1; j <= n; j++) {
a[j] = 0;
}
} else {
String[] st = s.split(" ");
int y = Integer.parseInt(st[1]);
if (a[y] != 1) {
a[y] = 1;
open++;
}
}
System.out.println(open);
}
sc.close();
}
}
sc.nextInt() does not scan the carriage return symbol. You need to make sure to scan that before trying to parse the next input.
e.g.:
import java.util.*;
public class TweetClose {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
int k = sc.nextInt();
sc.nextLine();
int open = 0;
int[] a = new int[50];
for (int i = 1; i <= n; i++) {
a[i] = 0;
}
for (int i = 0; i < k; i++) {
String s = sc.nextLine();
if (s.equals("CLOSEALL")) {
open = 0;
for (int j = 1; j <= n; j++) {
a[j] = 0;
}
} else {
String[] st = s.split(" ");
int y = Integer.parseInt(st[1]);
if (a[y] != 1) {
a[y] = 1;
open++;
}
}
System.out.println(open);
}
sc.close();
}
}
The problem caused by using nextLine(). You should use next() instead because you want to process the next token.
After processing all tokens, the final line-break of the current line is still in memory. nextLine() returns that line break "\n". Then you process it:
String[] st = s.split(" ");
int y = Integer.parseInt(st[1]);
The split function returns an array with only one element (the "\n"), therefore you cannot parse st[1]. There is no such element, only st[0] exists.
It will work with next() instead of nextLine() because next() skips over the line break and proceeds with the next token of the next line.
This is a very common mistake because there is no nextString() function.

How do I ignore the double but pass the rest of the ints into an array in a txt file?

I am doing a Java exercise which requires me to read a file that contains numbers (includes ints and doubles) and loop them into an array. However, the code below only stops at the first double and then doesn't continue on. What do I have to do to skip over that Double (and ones that come up later on) and continue displaying the ints?
int index = 0;
Scanner scan1 = new Scanner(new File(fileName));
while(scan1.hasNextInt()) {
index = index + 1;
scan1.nextInt();
}
int[] numbers = new int[index];
Scanner scan2 = new Scanner(new File(fileName));
for(int i = 0; i < index; i++) {
numbers[i] = scan2.nextInt();
}
return numbers;
Updated code:
public int[] readNumbers2(String fileName) throws Exception {
int index = 0;
Scanner scan1 = new Scanner(new File(fileName));
while(scan1.hasNext()) {
if(scan1.hasNextInt()) {
index = index + 1;
scan1.nextInt();
} else {
scan1.next();
}
}
int[] numbers = new int[index];
Scanner scan2 = new Scanner(new File(fileName));
for(int i = 0; i < index; i++) {
numbers[i] = scan2.nextInt();
}
return numbers;
}
Not a complete answer but this loop may be better suited for you:
while (scan1.hasNext()) {
if (scan1.hasNextInt()) {
// do something with int
} else {
// move past non-int token
scan1.next();
}
}
So for example:
public static void main (String args[]) {
Scanner scan1 = new Scanner("hello 1 2 3.5 there");
while (scan1.hasNext()) {
if (scan1.hasNextInt()) {
// do something with int
int i = scan1.nextInt();
System.out.println(i);
} else {
// move past non-int token
scan1.next();
}
}
}
prints:
1
2
Here's a version based on your updated code post:
Scanner scan1 = new Scanner("hello 1 2 3.5 there");
int index = 0;
while(scan1.hasNext()) {
if(scan1.hasNextInt()) {
index = index + 1;
scan1.nextInt();
} else {
scan1.next();
}
}
System.out.println("there are "+index+" integer tokens");
int[] numbers = new int[index];
int i = 0;
Scanner scan2 = new Scanner("hello 1 2 3.5 there");
while(scan2.hasNext()) {
if(scan2.hasNextInt()) {
numbers[i++] = scan2.nextInt();
} else {
scan2.next();
}
}
for (int j = 0; j < numbers.length; j++) {
System.out.println(numbers[j]);
}
prints
there are 2 integer tokens
1
2

Number BreakingDown

So I was asked to do a code that returns the broken down version of the given number. The output should be like this:
Number to break down: 123045011
100000000
20000000
3000000
0
40000
5000
0
10
1
But what my program does is this:
Number to break down: 123045011
100000001
100000002
100000003
100000000
100000004
100000005
100000000
100000001
100000001
This is my code.
import java.util.Scanner;
public class NumberBreakdown {
public static String brokeDownNumber(int num) {
String numberBrokenDown = "";
int numLength = Integer.toString(num).length();
String numAsString = Integer.toString(num);
for(int i = 0; i < numLength; i++) {
// convert Integer to string by using Integer.toString(varToConvert);
// convert char to String by using Character.toString(varToConvert)
int currentNum = Integer.parseInt(Character.toString(numAsString.charAt(i)));
currentNum += Math.pow(10,numLength - 1);
numberBrokenDown += Integer.toString(currentNum) + "\n";
}
return numberBrokenDown;
}
public static void main(String[] args) {
// no need to change this
Scanner reader = new Scanner(System.in);
System.out.print("Number to break down: ");
int number = Integer.parseInt(reader.nextLine());
System.out.println(brokeDownNumber(number));
}
}
What should I change/do?
Change your for loop as below -
for(int i = 0; i < numLength; i++) {
// convert Integer to string by using Integer.toString(varToConvert);
// convert char to String by using Character.toString(varToConvert)
int currentNum = Integer.parseInt(Character.toString(numAsString.charAt(i)));
int currentNum2 = currentNum*(int) Math.pow(10,numLength - i -1);
numberBrokenDown += Integer.toString(currentNum2) + "\n";
}
Only one line code change is needed.
currentNum *= (int)Math.pow(10, numLength - i - 1);
In each iteration, 10's power should decrease. So, numLength - i - 1 is needed.
+= is changed to *= because currentNum should be multiplied by 10th power to get desired result.
public class NumberBreakdown {
public static String brokeDownNumber(int num) {
String numberBrokenDown = "";
String numAsString = Integer.toString(num);
int numLength = numAsString.length();
for(int i = 0; i < numLength; i++) {
// convert Integer to string by using Integer.toString(varToConvert);
// convert char to String by using Character.toString(varToConvert)
int currentNum = num%10;
num = num/10;
if(currentNum ==0) {
System.out.print("0");
}else {
// currentNum += Math.pow(10,numLength - 1);
// numberBrokenDown += Integer.toString(currentNum) + "\n";
System.out.print(currentNum);
for(int j=0;j<i;j++)
System.out.print("0");
}
System.out.println("");
}
return numberBrokenDown;
}
public static void main(String[] args) {
// no need to change this
Scanner reader = new Scanner(System.in);
System.out.print("Number to break down: ");
int number = Integer.parseInt(reader.nextLine());
brokeDownNumber(number);
}
}

Java Array Index Out of Bounds Exception [duplicate]

This question already has an answer here:
Closed 10 years ago.
I run through the entire code. I am able to enter a simple .txt file to search for a word. After it asks for a word, it returns
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -48
at SearchEngine.main(SearchEngine.java:150)
Line 150 is for (int j = 0; j
Any help debugging?
This is basic search engine program that should be able to search a .txt file for any word.
Assignment link: http://cis-linux1.temple.edu/~yates/cis1068/sp12/homeworks/concordance/concordance.html
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();
}
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; j++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
} } }
}
lineNum++;
}
System.out.println("Finished creating invertedIndex");
}
System.out.println("Enter a word to be searched (type quit to exit program)");
Scanner keyboard = new Scanner(System.in);
String searchWord = keyboard.next();
while (!searchWord.equals("quit")) {
int counter = 0;
int wordPos = Arrays.binarySearch(allWordsArray, searchWord);
for (int j = 0; j<invertedIndex[wordPos].length; j++) {
if(invertedIndex[wordPos][j] != 0) {
int number = invertedIndex[wordPos][j];
String printOut = concordanceArray[number];
System.out.print(number);
System.out.print(" :");
System.out.println(printOut);
}
}
}
catch (FileNotFoundException exception) {
System.out.println("File Not Found");
}
} //main
} //class
From what I can see your getNumOfDistinctWords(String[] x) is wrong. This is returning a value of one less than it should be. Here is a modified version of the code:
import java.util.*;
import java.io.*;
public class SearchEngine {
//Counts the number of words in the file
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 String[] getNumOfDistinctWords (String[] x) throws FileNotFoundException {
HashSet<String> distinctWords = new HashSet<String>();
for(int i=0; i<x.length; i++){
distinctWords.add(x[i]);
}
String[] distinctWordsArray = new String[distinctWords.size()];
int i = 0;
for(String word : distinctWords){
distinctWordsArray[i] = word;
i++;
}
return distinctWordsArray;
}
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();
}
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);
//Output the number of words in the file
System.out.println("Number of words is: " + NUM_WORDS);
String[] allWordsArray = new String[NUM_WORDS];
readInWords(input, allWordsArray);
Arrays.sort(allWordsArray);
String[] distinctWordsArray = getNumOfDistinctWords(allWordsArray);
//Output the number of distinct words
System.out.println("Number of distinct words is: " + distinctWordsArray.length);
System.out.println("Finished creating distinctWordsArray");
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[distinctWordsArray.length][10];
int [] wordCountArray = new int[distinctWordsArray.length];
int lineNum = 0;
while (lineNum < concordanceArray.length) {
Scanner scan = new Scanner(concordanceArray[lineNum]);
while (scan.hasNext()) {
//Find the position the word appears on the line, if word not found returns a number less than 0
int wordPos = Arrays.binarySearch(distinctWordsArray, scan.next());
if(wordPos > -1){
wordCountArray[wordPos] += 1;
}
for(int i = 0; i < invertedIndex.length; i++) {
for(int j = 0; j < invertedIndex[i].length; j++) {
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
I should also point out the fact that Arrays.binarySearch(distinctWordsArray, scan.next()); will return a number less than 0 if the word is not found on that line. This is why you are getting the Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 as wordCountArray is being referenced at index -1 which of course doesn't exist!
The code after this also looks buggy but I'll let you fix that!!
Without knowing exactly where line 126 is, finding this specific bug is just too much hassle. But I've got some advice for the rest of the code:
int NUM_DISTINCT_WORDS = getNumOfDistinctWords(input, wordArray);
Normally, variables in all-caps are constants that are assigned at compile time. It's a tradition that comes from C days, when it was wonderful to know which "variables" were actually replaced by the preprocessor. But the convention has proven to be useful in other languages, and most programmers would expect NUM_DISTINCT_WORDS to be assigned a specific value at compile time.
This code is simply unreadable:
for(int i = 0; i < invertedIndex.length; i++) {
for(int j = 0; j < invertedIndex[i].length; j++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
} } }
A more idiomatic way to show these nested loops is:
for (int i = 0; i < invertedIndex.length; i++) {
for (int j = 0; j < invertedIndex[i].length; j++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
}
}
}
Because I use the standard Lindent script to do re-indenting, I get tabs. You don't have to use tabs, but they are convenient to add and delete with a single keystroke, and they are deep enough to be obviously visible even with smallish type faces. You'll find your code far easier to work with if you follow the standard indenting idioms.
The following piece of code is extremely unfortunate:
catch(FileNotFoundException exception) {
System.out.println("File Not Found");
}
It would be better to catch a higher-level exception and include the exception message. You can more easily handle dozens of errors if you catch an exception higher in the hierarchy, and the error messages will be far more informative.
Your main() method performs a lot of detailed work. I think your code would be easier to test, easier to debug, and easier to read, if you break it apart into more methods. Try to get the main() to read practically like a high-level description of your code.
With the line with the bug on it now easily visible, I can spot the problem:
int wordPos = Arrays.binarySearch(vocabArray, scan.next());
wordCountArray[wordPos]+=1;
You've looked up the wordPos in the vocabArray, but modified content in the wordCountArray. Are you sure they are the same size and have the same meanings?

Java Search Engine Debugging [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I run through the entire code. I am able to enter a simple .txt file to search for a word. After it asks for a word, it returns
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -48 at SearchEngine.main(SearchEngine.java:150)
Line 150 is for (int j = 0; j
Any help debugging?
This is basic search engine program that should be able to search a .txt file for any word.
Assignment link: http://cis-linux1.temple.edu/~yates/cis1068/sp12/homeworks/concordance/concordance.html
import java.util.*;
import java.io.*;
public class SearchEngine {
//Counts the number of words in the file
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 String[] getNumOfDistinctWords (String[] x) throws FileNotFoundException {
HashSet<String> distinctWords = new HashSet<String>();
for(int i=0; i<x.length; i++){
distinctWords.add(x[i]);
}
String[] distinctWordsArray = new String[distinctWords.size()];
int i = 0;
for(String word : distinctWords){
distinctWordsArray[i] = word;
i++;
}
return distinctWordsArray;
}
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();
}
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);
//Output the number of words in the file
System.out.println("Number of words is: " + NUM_WORDS);
String[] allWordsArray = new String[NUM_WORDS];
readInWords(input, allWordsArray);
Arrays.sort(allWordsArray);
String[] distinctWordsArray = getNumOfDistinctWords(allWordsArray);
//Output the number of distinct words
System.out.println("Number of distinct words is: " + distinctWordsArray.length);
System.out.println("Finished creating distinctWordsArray");
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[distinctWordsArray.length][10];
int [] wordCountArray = new int[distinctWordsArray.length];
int lineNum = 0;
while (lineNum < concordanceArray.length) {
Scanner scan = new Scanner(concordanceArray[lineNum]);
while (scan.hasNext()) {
//Find the position the word appears on the line, if word not found returns a number less than 0
int wordPos = Arrays.binarySearch(distinctWordsArray, scan.next());
if(wordPos > -1){
wordCountArray[wordPos] += 1;
}
for(int i = 0; i < invertedIndex.length; i++) {
for(int j = 0; j < invertedIndex[i].length; j++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
}
}
}
}
lineNum++;
}
System.out.println("Finished creating invertedIndex");
System.out.println("Enter a word to be searched (type quit to exit program)");
Scanner keyboard = new Scanner(System.in);
String searchWord = keyboard.next();
while (!searchWord.equals("quit")) {
int counter = 0;
int wordPos = Arrays.binarySearch(allWordsArray, searchWord);
for (int j = 0; j<invertedIndex[wordPos].length; j++) {
if(invertedIndex[wordPos][j] != 0) {
int number = invertedIndex[wordPos][j];
String printOut = concordanceArray[number];
System.out.print(number);
System.out.print(" :");
System.out.println(printOut);
}
}
}
}
catch (FileNotFoundException exception) {
System.out.println("File Not Found");
}
} //main
} //class
int wordPos = Arrays.binarySearch(allWordsArray, searchWord);
wordPos will be negative when the searchWord is not in the array. Therefore,
in for (int j = 0; j<invertedIndex[wordPos].length; j++) {, invertedIndex[wordPos] will be trying to access a negative index of the array, in your case, -48
You should do something like this before the loop:
if(wordPos < 0){
// Do something
}else {
for (int j = 0; j<invertedIndex[wordPos].length; j++) {
...
}
You should read the Javadoc, specially the doc for returns. You will get your answer about -48.

Categories

Resources