Reading from a file into an array of objects - java

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;
}

Related

How do I read data from text file to ArrayList

Assume that entered file have the following data:
101
alice
102
bob
103
smith
All this data into textfile, as it's shown in program, just enter text file name and read all data and display.
I wanna read those two data (number and name ) into ArrayList and display all the data as what I've shown in the program:
class Student {
private int num;
private String name;
public Student(int num, String name) {
this.num = num;
this.name= name;
}
public String toString() {
return "[ student number :: "+num+" ] \t [ student name ::
"+name+ "]";
}
}
import java.io.*;
import java.util.*;
class Tester {
public static void main(String [] aa)throws IOException {
Scanner kb=new Scanner(System.in);
System.out.print(" enter file name >> ");
String filename=kb.nextLine();
File f = new File(filename);
kb=new Scanner(f);
ArrayList<Student> stu =new ArrayList<Student>();
while(kb.hasNextLine()) {
int num=kb.nextInt();kb.nextLine();
String name =kb.nextLine();
stu.add(num);
stu.add(name);
}
for(int i=0;i<stu.size(); i++) {
System.out.println(stu.get(i));
}
}
}
Since you already made an arraylist of student you can do this inside your text reader(while loop): stu.add(new Student(num, name)); what it does is you are creating an object of student and placing it inside the arraylist for every record in your text file.
Your program should return an error because are attempting to put a String and int into an ArrayList of Students. Also, you only iterates through your ArrayList of students and do not print them out. Your code should look like this.
class Tester {
public static void main(String[] aa) throws IOException {
Scanner kb = new Scanner(System.in);
System.out.print(" enter file name >> ");
String filename = kb.nextLine();
File f = new File(filename);
kb = new Scanner(f);
ArrayList<Student> stu = new ArrayList<Student>();
while (kb.hasNextLine()) {
int num = kb.nextInt();
kb.nextLine();
String name = kb.nextLine();
stu.add(new Student(num, name));
}
for (Student s : stu) {
System.out.println(s.toString());
}
}
}
public class Tester {
public static void main(String[] args) {
String path = "E:\\b.txt";
Tester tester = new Tester();
String[] str = tester.sortData(tester.readFile(path));
List<Student> list = new ArrayList<Student>();
for(int i = 0;i < str.length;i = i + 2){
Student student = new Student();
student.setNum(Integer.parseInt(str[i]));
student.setName(str[i + 1]);
list.add(student);
}
for(int i = 0;i < list.size();i++){
System.out.println(list.get(i).getNum() + " " + list.get(i).getName());
}
}
public StringBuilder readFile(String path){
File file = new File(path);
StringBuilder stringBuilder = new StringBuilder();
try{
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String lineTxt = null;
while((lineTxt = bufferedReader.readLine()) != null){
stringBuilder.append(lineTxt);
}
}catch(Exception e){
System.out.println("erro");
}
return stringBuilder;
}
public String[] sortData(StringBuilder words){
int i = 0;
int count = 0;
String str = "\\d+.\\d+|\\w+";
Pattern pattern = Pattern.compile(str);
Matcher ma = pattern.matcher(words);
String[] data = new String[6];
while(ma.find()){
data[i] = ma.group();
i++;
}
return data;
}
}
class Student{
private int num;
private String name;
public Student(){
}
public Student(int num, String name) {
super();
this.num = num;
this.name = name;
}
public String toString() {
return "Student [num=" + num + ", name=" + name + "]";
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Suppose your file looks like this
101 alice
102 bob
103 smith
String fileName = //get by scanner;
//read file into stream, try-with-resources
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
List<Student> users = new ArrayList<>();
stream.stream().forEach(user -> {
List<String> userAttrs = Arrays.asList(user.split("\\s* \\s*"));
Student userObj = new Student(Integer.parseInt(userAttrs.get(0)), userAttrs.get(1));
users.add(userObj);
});
users.stream().forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
After I enter first answer problem was edited and now your file looks like
101
alice
102 bob
103 smith
String fileName = //get by scanner;
//read file into stream, try-with-resources
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
List<String> detailList = stream.collect(Collectors.toList());
List<Student> students = new ArrayList<>();
BiFunction<String, String, Student> userFunction = (id, name) ->
new Student(Integer.parseInt(id), name);
for (int i = 0; i < detailList.size(); i += 2) {
students.add(userFunction.apply(
detailList.get(i), detailList.get(i+1)));
}
students.stream().forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}

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(" ");

UPDATED: Reading text file into a byte array

For a homework assignment, I need to create a class that that can read and write Byte arrays to/from a file. I have successfully created classes that can read and write CSV and text, however I am having some difficulty, when it comes to arrays. The code below is features the class that I have written. It is largely based on my CSV class, the FileInput class http://www.devjavasoft.org/SecondEdition/SourceCode/Share/FileInput.java) and FileOutput Class (http://www.devjavasoft.org/SecondEdition/SourceCode/Share/FileOutput.java).
When running the program to read a text file I get the following error message:
"Exception in thread "main" java.lang.NullPointerException
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:101)
at java.io.FileReader.<init>(FileReader.java:58)
at com.gc01.FileManager.FileInput.<init>(FileInput.java:22)
at com.gc01.FileManager.ByteManager.readByte(ByteManager.java:28)
at com.gc01.FileManager.ByteManager.main(ByteManager.java:85)"
And my code:
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ByteManager {
public String getByteFile(){
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the file directory of the chosen txt file?");
System.out.println("For Example: /Users/UserName/Downloads/FileName.txt");
///Users/ReeceAkhtar/Desktop/FileName.txt
final String fileName = sc.nextLine();
System.out.println("How many columns are in the file?");
final int columns = sc.nextByte();
System.out.println("How many rows are in the file?");
final int rows = sc.nextByte();
return fileName;
}
public void readByte(final String fileName, int columns, int rows){
FileInput in = new FileInput(fileName);
int [] [] data = new int[rows] [columns];
String [] line;
for (int i = 0; i < rows; i++){
line = in.readString().split("\t");
for (int j = 0; j < columns; i++){
data [i][j] = Byte.parseByte(line[j]);
}
}
System.out.println("******File Read*****");
}
public String chooseFileOutput(){
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the file directory for the output of the chosen file");
System.out.println("For Example: /Users/UserName/Downloads/FileName.txt");
///Users/ReeceAkhtar/Desktop/GeoIPCountryWhois.csv
final String fileNameOUT = sc.nextLine();
System.out.println("How many columns are in the file?");
final int columnsOut = sc.nextByte();
System.out.println("How many rows are in the file?");
final int rowsOut = sc.nextByte();
return fileNameOUT;
}
public void writeByte(final String fileNameOUT, int columnsOut, int rowsOut){
FileOutput createData = new FileOutput (fileNameOUT);
int newData = 0;
System.out.println("Enter data. To finish, enter 'TERMINATE_FILE'");
while(!"TERMINATE_FILE".equals(newData)){
Scanner input = new Scanner (System.in);
int [] [] data = new int[rowsOut] [columnsOut];
String [] line = null;
for (int i = 0; i < rowsOut; i++){
createData.writeInteger(newData = input.nextByte());
System.out.println("\t");
for (int j = 0; j < columnsOut; i++){
data [i][j] = Byte.parseByte(line[j]);
}
}
createData.close();
}
}
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
final ByteManager object = new ByteManager ();
System.out.println("1 for Read File, 2 for Write file");
String choice = in.nextLine();
if("1".equals(choice)){
object.getByteFile();
object.readByte(null, 0, 0);
} else if ("2".equals(choice)){
object.chooseFileOutput();
object.writeByte(null, 0, 0);
} else{
System.out.println("Goodbye!");
System.exit(0);
}
}
}
UPDATE
Thank you for your comments and advice below, I have now run into a another problem that I can not work out. I have re-written my readByte method. However when I now run it, I no longer get compiler errors (thanks to your advice), however I can not get the contents of the file to print. Instead the console just displays "File Read". I have studied various resources yet I can not find the solution. I am sure it is a simple mistake somewhere. The contents of the file I am trying to read is also below.
public String getByteFile(){
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the file directory of the chosen txt file?");
System.out.println("For Example: /Users/UserName/Downloads/FileName.txt");
///Users/ReeceAkhtar/Desktop/FileName.txt
final String fileName = sc.nextLine();
System.out.println("How many columns are in the file?");
final int columns = sc.nextInt();
System.out.println("How many rows are in the file?");
final int rows = sc.nextInt();
return fileName;
}
public void readByte(final String fileName, int rows,int columns){
BufferedReader br = null;
String[] line;
String splitBy = "\t";
int [][] data = new int[rows] [columns];
try {
br = new BufferedReader(new FileReader(fileName));
for (int i = 0; i < rows; i++){
line = br.toString().split(splitBy);
for (int j = 0; j < columns; j++){
data[i] [j] = Integer.parseInt(line[j]);
System.out.println(data[i][j]);
}
}
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("*****File Read*****");
}
File Contents (separated by tab)
123 6565
123 6564
123 6563
123 6562
This code is the source of the error
object.readByte(null, 0, 0);
The parameter null is invalid state for FileInput. It should be a file name string.
You are passing null argument to readByte() from main()
object.readByte(null, 0, 0);
And in readByte()
FileInput in = new FileInput(fileName); //here it throws NPE
Pass valid file name.
NullPointerException
public class NullPointerException
extends RuntimeException
Thrown when an application attempts to use null in a case where an object is required. These include:
Calling the instance method of a null object.
Accessing or modifying the field of a null object.
Taking the length of null as if it were an array.
Accessing or modifying the slots of null as if it were an array.
Throwing null as if it were a Throwable value.

Cannnot find "Array Out of Bounds Exception" 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.

Array Required, but found Int

I'm running into an issue when converting some code for another project and was hoping for a bit of help. In the 'readFile' method, I am trying to parse a String to integers when I read the file. However, it is giving me the error 'array found, but int required'
import java.util.*;
import java.io.*;
public class JavaApplication1
{
static int [] matrix = new int [10];
static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException
{
String fileName = "Integers.txt";
// read the file
readFile(fileName);
// print the matrix
printArray(fileName, matrix);
}
// Read File
public static void readFile(String fileName) throws IOException
{
String line = "";
FileInputStream inputStream = new FileInputStream(fileName);
Scanner scanner = new Scanner(inputStream);
DataInputStream in = new DataInputStream(inputStream);
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
int lineCount = 0;
String[] numbers;
while ((line = bf.readLine()) != null)
{
numbers = line.split(" ");
for (int i = 0; i < 10; i++)
{
matrix[lineCount][i] = Integer.parseInt(numbers[i]);
}
lineCount++;
}
bf.close();
}
public static void printToFile(String fileName, String output) throws IOException
{
java.io.File file = new java.io.File(fileName);
try (PrintWriter writer = new PrintWriter(file))
{
writer.print(output);
}
}
public static void printArray(String fileName, int [] array)
{
System.out.println("The matrix is:");
for (int i = 0; i < 10; i++)
{
System.out.println();
}
System.out.println();
}
}
matrix is an array of type int, which means matrix[lineCount] is an int.
You are tryng to do matrix[lineCount][i] which is getting the place i of an int.
That is why you are getting that error.
I guess you wanted matrix to be int[][] matrix = new int[10][10];
matrix[lineCount][i] = Integer.parseInt(numbers[i]);
is wrong.
Should be either
matrix[lineCount]= Integer.parseInt(numbers[i]);
OR
matrix[i]= Integer.parseInt(numbers[i]);

Categories