Getting array index out of bounds exception but don't know why? - java

I am trying to create a split() method that reads a file, line by line, then separates the Strings and Integers into an array that is then written to another file. I have created an array to hold each String called list and one to hold the Integers called scores.
When I try to run my code, it reaches the second element in the list array which is surname = list[1] and then I get the error.
What I am trying to eventually do is split each element and get the average of the Integers so the original line of text would read Mildred Bush 45 65 45 67 65 and my new line of text would read Bush, Mildred: Final score is x.xx.
The error happens at line 7 surname = list[1];
My code:
public void splitTest()
{
String forename, surname, tempStr, InputFileName, OutputFileName;
tempStr = "";
String[] list = new String[6];
list = tempStr.split(" ");
forename = list[0];
surname = list[1];
int[] scores = new int[5];
scores[0] = Integer.parseInt(list[2]);
scores[1] = Integer.parseInt(list[3]);
scores[2] = Integer.parseInt(list[4]);
scores[3] = Integer.parseInt(list[5]);
scores[4] = Integer.parseInt(list[6]);
FileReader fileReader = null;
BufferedReader bufferedReader = null;
FileOutputStream outputStream = null;
PrintWriter printWriter = null;
clrscr();
System.out.println("Please enter the name of the file that is to be READ (e.g. details.txt) : ");
InputFileName = Genio.getString();
System.out.println("Please enter the name of the file that is to be WRITTEN TO (e.g. newDetails.txt) : ");
OutputFileName = Genio.getString();
try {
fileReader = new FileReader(InputFileName);
bufferedReader = new BufferedReader(fileReader);
outputStream = new FileOutputStream(OutputFileName);
printWriter = new PrintWriter(outputStream);
tempStr = bufferedReader.readLine();
while (tempStr != null) {
System.out.println(tempStr);
printWriter.write(tempStr+"\n");
tempStr = bufferedReader.readLine();
}
System.out.println("\n\nYOUR NEW FILE DATA IS DISPLAYED ABOVE!\n\n");
pressKey();
bufferedReader.close();
printWriter.close();
} catch (IOException e) {
System.out.println("Sorry, there has been a problem opening or reading from the file");
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
System.out.println("An error occurred when attempting to close the file");
}
}
if(printWriter != null) {
printWriter.close();
}
}
}
Where it says Genio, this a class that deals with user input.

You initialize the list array with
list = tempStr.split(" ");
The size of that array can be anything. It depends on the number of spaces in tempStr.
You have to check the length of list before accessing its elements.
If you expect the input to contain a certain number of parameters, add a check :
list = tempStr.split(" ");
int[] scores = new int[5];
if (list.length > 6) {
forename = list[0];
surname = list[1];
scores[0] = Integer.parseInt(list[2]);
scores[1] = Integer.parseInt(list[3]);
scores[2] = Integer.parseInt(list[4]);
scores[3] = Integer.parseInt(list[5]);
scores[4] = Integer.parseInt(list[6]);
}
This would prevent the exception. Of course, you have to decide how to handle the situation in which the condition is false.
EDIT :
tempStr = "";
This means there would be exactly one element in list. I'm assuming you meant to put some actual value in this variable.

Related

my java program is not working after I execute file io

Hello so i have an assignment and my code is not working. I ask a user to input a filename and after that it freezes and does not process the number of lines. im doing something wrong but im not sure what? can someone please help me im really desperate this part is crashing my whole program and i might fail and i dont know who to ask :( for help
public static void fileReader()
{
Scanner sc = new Scanner(System.in);
int catNum;
int dogNum;
int fishNum;
String fileName;
System.out.println("Please enter the Name of the file you want to read in
from");
fileName = sc.nextLine();
System.out.println("this is the file name --> "+fileName);
catNum = TestFile.getNum(fileName, "cat");
dogNum = TestFile.getNum(fileName, "dog");
fishNum = TestFile.getNum(fileName, "fish");
System.out.println("THE CAT IS" +catNum);
System.out.println("THE DOG IS" +dogNum);
System.out.println("THE FISH IS" +fishNum);
}
i dont see anything wrong after i ask for the file name it freezes
public static int getNum (String fileName, String word) {
Scanner sc = new Scanner(System.in);
int lineNum = 0;
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String line;
try {
fileStrm = new FileInputStream (fileName);
rdr = new InputStreamReader (fileStrm);
bufRdr = new BufferedReader (rdr);
line = bufRdr.readLine();
while (line != null)
{
String firstWord = processString(line);
if(firstWord.equalsIgnoreCase(word)) //this submodule i going to get the number to create each array like e.g. how many states so that it can create it in country object
{
lineNum++;
line = bufRdr.readLine() ;
}
}
fileStrm.close();
}
catch (IOException e)
{
if (fileStrm != null)
{
try
{
fileStrm.close();
}
catch(IOException ex2)
{
System.out.println("This is Error");
}
}
System.out.println("error reading file !!" +e.getMessage());
}
return lineNum; }
the file looks something like this (each line is like this):
CAT:NAME=doopie:SHORTNAME=doop:LANGUAGE=English:AREA=America:POPULATION=2222:POPREF=Census2016
Look at this while loop:
while (line != null)
{
String firstWord = processString(line);
if(firstWord.equalsIgnoreCase(word)) //this submodule i going to get the number to create each array like e.g. how many states so that it can create it in country object
{
lineNum++;
line = bufRdr.readLine() ;
}
}
If firstWord.equalsIgnoreCase(word) returns false, then what will happen? The value of line will never be updated and the loop will never exit.

combine two methods in Java together in this Java code

I want combine the two methods Just some error in my document parser, frequencyCounter and parseFiles thsi code.
I want all of frequencyCounter should be a function that should be executed from within parseFiles, and relevant information don't worry about the file's content should be passed to doSomething so that it knows what to print.
Right now I'm just keep messing up on how to put these two methods together, please give some advices
this is my main class:
public class Yolo {
public static void frodo() throws Exception {
int n; // number of keywords
Scanner sc = new Scanner(System.in);
System.out.println("number of keywords : ");
n = sc.nextInt();
for (int j = 0; j <= n; j++) {
Scanner scan = new Scanner(System.in);
System.out.println("give the testword : ");
String testWord = scan.next();
System.out.println(testWord);
File document = new File("path//to//doc1.txt");
boolean check = true;
try {
FileInputStream fstream = new FileInputStream(document);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
strLine = br.readLine();
// Read File Line By Line
int count = 0;
while ((strLine = br.readLine()) != null) {
// check to see whether testWord occurs at least once in the
// line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if (check) {
// get the line
String[] lineWords = strLine.split("\\s+");
// System.out.println(strLine);
count++;
}
}
System.out.println(testWord + "frequency: " + count);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The code below gives you this output:
Professor frequency: 54
engineering frequency: 188
data frequency: 2
mining frequency: 2
research frequency: 9
Though this is only for doc1, you've to add a loop to iterate on all the 5 documents.
public class yolo {
public static void frodo() throws Exception {
String[] keywords = { "Professor" , "engineering" , "data" , "mining" , "research"};
for(int i=0; i< keywords.length; i++){
String testWord = keywords[i];
File document = new File("path//to//doc1.txt");
boolean check = true;
try {
FileInputStream fstream = new FileInputStream(document);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
strLine = br.readLine();
// Read File Line By Line
int count = 0;
while ((strLine = br.readLine()) != null) {
// check to see whether testWord occurs at least once in the
// line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if (check) {
// get the line
String[] lineWords = strLine.split("\\s+");
count++;
}
}
System.out.println(testWord + "frequency: " + count);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
hope this helps!

Overwriting a line in java txt file

So I have created this method which at the end displays the whole line because i am displaying the array after converting and editing it. So my Question is how can i know overwrite the array to the same line i grabbed it from. thanks in advance and here is my code.
public void getData(String path, String accountNumber) {
try {
FileInputStream fis = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
System.out.println("Please Enter the Deposit amount That you would like to add.");
Scanner sn = new Scanner (System.in);
int add = sn.nextInt();
String str;
while ((str = br.readLine()) != null) {
if (str.contains(accountNumber)) {
String[] array = str.split(" ");
int old = Integer.parseInt(array[3]);
int Sum= old + add;
String Sumf = Integer.toString(Sum);
array[3] = Sumf;
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);}
break;
}
}
} catch (Exception ex) {
System.out.println(ex);
}
}
i am using string accountNumber to grab the specific line that i need. after getting the line i am changing it to an array while splitting the index with str.split(" "); . After that i know that i need to edit index number [3]. so i do so and then i put it back into the array. the final thing i need to do is to right the array back now.
You can keep track of the input from the file you are reading and write it back with the modified version.
public void getData(String path, String accountNumber) {
try {
FileInputStream fis = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
System.out.println("Please Enter the Deposit amount That you would like to add.");
Scanner sn = new Scanner (System.in);
int add = sn.nextInt();
String line; // current line
String input = ""; // overall input
while ((line = br.readLine()) != null) {
if (line.contains(accountNumber)) {
String[] array = line.split(" ");
int old = Integer.parseInt(array[3]);
int Sum= old + add;
String Sumf = Integer.toString(Sum);
array[3] = Sumf;
// rebuild the 'line' string with the modified value
line = "";
for (int i = 0; i < array.length; i++)
line+=array[i]+" ";
line = line.substring(0,line.length()-1); // remove the final space
}
// add the 'line' string to the overall input
input+=line+"\n";
}
// write the 'input' String with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream(path);
fileOut.write(input.getBytes());
fileOut.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
This is how i understand the question that you have a file you will read it line by line and will make some changes and want to write it again at the same position. Create a new temp file and write the contents to the temp file, if changed write the changed result if not write it as it is.
And at last rename the temp to your original file name

JAVA: read .txt file and store doubles into array

I have the following code already, which goes as far as appending the doubles.
Scanner sc1 = new Scanner(System.in);
try {
System.out.println("Enter filename:");
String name = sc1.nextLine();//determines name of file
File file = new File(name);//creates above file
FileReader fileReader = new FileReader(file);//file is read
BufferedReader bufferedReader = new BufferedReader(fileReader );//BufferReader reads file, line by line
StringBuffer stringBuffer = new StringBuffer();//appended to StringBuffer
String line;//reads each
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line + "\n");
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
}
catch (IOException e)
{
e.printStackTrace();
}
The code reads a file that has a double on each line
ex:
1
2
3
4
5
...
How do I store each of these doubles into an array?
If you want to stick to using Array only, convert StringBuffer to String[] like this:
String [] stringArray = stringBuffer.split("\n");
Then convert string array to double array:
Double [] doubleArray = new Double[stringArray.size];
for(int i=0 : i < stringArray.size : i++){
doubleArray[i] = Doube.parseDouble(stringArray[i]);
}
If you must use StringBuffer, you can divide into array by StringTokenizer class.
Alternatively, you can use String instead of StringBuffer and then split() method will work with de-limiter.
You could use an ArrayList:
ArrayList<Double> doubles = new ArrayList<Double>();
while ((line = bufferedReader.readLine()) != null)
{
doubles.add(Double.parseDouble(line));
}
Basic solution
ArrayList<Double> doubles = new ArrayList<>();
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line + "\n");
try{
double value = Double.parseDouble(line );
doubles.add(value);
} catch(NullPointerException e){
//null string
} catch(NumberFormatException e){
//no parsable on the current line
}
}
I don't get the problem...Just make an array that stores the contents of the line as the file is read.

Fixing a nullpointerexception in Java

I have a 2d array being written to a file from another method. I've defined the contents of the 2d array in my sightings method, but when it passes over to the save method the contents (in at least block [1] [1]) become null. How do I go about making sure the value remains defined?
My code so far:
(Sightings Method)
public void Sighting()
{
Scanner input = new Scanner (System.in);
String MigChoice; //initiates Migrant Choice variable to be stored
String Trail; //initiates Trail to be stored
String NumberSeen; //initiates number to be stored
String Species; //initiates species to be stored
String Date; //initiates date to be stored
String[][] EntryList;
EntryList = new String [500][5];
System.out.print("What species of bird was observed?\n");
Species = input.nextLine();
System.out.print("What trail did this spotting take place on?\nDirectory:\n");
System.out.println("1). Alligator Alley");
System.out.println("2). Eagle Roost");
System.out.println("3). Heron Hideout");
System.out.println("4). Lost Bridge Trail");
System.out.println("5). Marsh Rabbit Run");
System.out.println("6). Otter");
System.out.println("7). Shady Oak");
System.out.println("8). Wading Bird Way");
System.out.println("9). Windmill Whisper");
Trail = input.nextLine();
System.out.println("The species is:\n1.)Migrant\n2.)Residential");
System.out.print("Please enter Migrant or Residential: ");
MigChoice = input.next();
System.out.print("What was the time of this sighting (in mm/dd/yyyy format)?\n");
Date = input.next();
System.out.print("Finally, how many birds were observed?\n");
NumberSeen = input.next();
EntryList [0][0] = Species;
EntryList [0][1] = Trail;
EntryList [0][2] = MigChoice;
EntryList [0][3] = Date;
EntryList [0][4] = NumberSeen;
Save(EntryList);
System.out.print("Thank you for adding an entry!");
System.out.println("Returning to main menu");
Menu();
}
(Save Method)
public void Save(String[][] EntryList) {
try {
String[][] content = EntryList;
File file = new File("CBB.dat");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
if (EntryList[0][0] != null) {
DataInputStream instream;
DataOutputStream outstream;
instream = new DataInputStream(new BufferedInputStream(
new FileInputStream(file))); // buffers the data stream
outstream = new DataOutputStream(new BufferedOutputStream(
new FileOutputStream(file)));
FileWriter fw = new FileWriter("CBB.dat", true);
BufferedWriter writer = new BufferedWriter(fw);
for (int row = 0; row < EntryList.length; row++) {
outstream.writeUTF(EntryList[row][0]);
outstream.writeUTF(EntryList[row][1]);
outstream.writeUTF(EntryList[row][2]);
outstream.writeUTF(EntryList[row][3]);
outstream.writeUTF(EntryList[row][4]);
}
outstream.close();
} else
System.out.print("Something is wrong");
} catch (IOException e) {
e.printStackTrace();
}
}
Error Message:
java.lang.NullPointerException
at java.io.DataOutputStream.writeUTF(DataOutputStream.java:330)
at java.io.DataOutputStream.writeUTF(DataOutputStream.java:306)
at Dossier.Save(Dossier.java:158)
at Dossier.Sighting(Dossier.java:133)
The writeUTF will be throw NullPointerException if you pass a null object as parameter.
Writes two bytes of length information to the output stream, followed
by the modified UTF-8 representation of every character in the string
s. If s is null, a NullPointerException is thrown. Each character in
the string s is converted to a group of one, two, or three bytes,
depending on the value of the character.
You can add null check if your loop:
for (int row = 0; row < EntryList.length; row++)
{
for(int col = 0; col < EntryList[row].length;col++) {
if(EntryList[row][col] != null)
outstream.writeUTF(EntryList[row][col]);
}
}

Categories