Reading table from a text file to a 2darray - java

i have a java code where i read a txt file, then iterate it so that i can fill it in a 2d array.
after i read the file i was able to print out its contents so i was sure that the file was read. and i was also sure that the bufferedreader library's .hasNextLine method was showing true when a line was found.
but when i used it in a while loop, it just acted as if no lines where found, thus it didnt iterate, hense i couldn't know how many rows i had in the table.==>
while (sc.hasNextLine()==true){ row++;}
furthermore, when i hard-coded the number of rows so that i could check if everything else was ok, i got a line not found error. please help me out.
i will link the code below.
package com.company;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void
main(String args[]) throws Exception {
int row=0;
int column=0;
int count=0;
BufferedReader x = new BufferedReader(new FileReader("src\\Table.txt"));
Scanner sc = new Scanner(x);
System.out.println(sc.nextLine()+sc.hasNextLine()+"\n"+sc.nextLine()+sc.hasNext()+"\n"+sc.nextLine()+"\n"+sc.nextLine()+sc.hasNextLine());
while (sc.hasNextLine()==true){ row++;}
System.out.println(row);
for (int i=0; i<row; i++) {
String[] line = sc.nextLine().trim().split(",");
System.out.println(line);
for (String line1 : line) {
if (",".equals(line1)) {
count++;
}
count+=1;
if(count>column){
column=count;
}
}
}
String [][] myArray = new String[row][column];
for (int i=0; i<myArray.length; i++) {
String[] line = sc.nextLine().trim().split(",");
for (int j=0; j<line.length; j++) {
myArray[i][j]= line[j];
}
}
System.out.println(Arrays.deepToString(myArray));
}
}
i also get this output
"C:\Program Files\Java\jdk-12.0.1\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2021.3.2\lib\idea_rt.jar=52205:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2021.3.2\bin" -Dfile.encoding=UTF-8 -classpath "C:\Users\acer pc\IdeaProjects\PDM\out\production\PDM" com.company.Main
CalculusII,Algebra,Networktrue
CalculusII,Algebra,Webtrue
CalculusIII,Prog2,Network
Algebra,Prog1,Webfalse
0
[]
Process finished with exit code 0

When you perform the following statement you've already read your entire file, so there are no lines left to read.
System.out.println(sc.nextLine()+sc.hasNextLine()+"\n"+sc.nextLine()+sc.hasNext()+"\n"+sc.nextLine()+"\n"+sc.nextLine()+sc.hasNextLine());
This is why your following iterations stop immediately and don't show the expected output. Maybe, what you were expecting was for the Scanner's internal cursor to reset itself once the end of file was reached. However, this is definitely not the behavior of the Scanner class (or any other), and none of its methods offer to reset or reposition the Scanner's cursor to a specific point of the file.
What you need to do is to close your connections and re-establish them in order to restart reading the content. For example, you could include every file consumption within a try block to automatically dispose every connection once you're done.
To simplify your code, in your first loop you could count the number of lines and check for the line with "the most columns", while in your second loop you could re-read the file's content.
public class Main {
public static void main(String args[]) {
int row = 0;
int column = 0;
int tmp = 0;
try (FileReader fr = new FileReader("src\\Table.txt");
BufferedReader br = (new BufferedReader(fr));
Scanner sc = new Scanner(br)) {
//First file consumption
while (sc.hasNextLine()) {
row++;
tmp = sc.nextLine().split(",").length;
if (tmp > column) {
column = tmp;
}
}
System.out.println(row);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
try (FileReader fr = new FileReader("src\\Table.txt");
BufferedReader br = (new BufferedReader(fr));
Scanner sc = new Scanner(br)) {
//Second file consumption
String[][] myArray = new String[row][column];
for (int i = 0; i < myArray.length; i++) {
String[] line = sc.nextLine().trim().split(",");
for (int j = 0; j < line.length; j++) {
myArray[i][j] = line[j];
}
}
System.out.println(Arrays.deepToString(myArray));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

Related

Scanner for input file and storing data objects from input file in array

Basically, I had to create a scanner for a given file and read through the file (the name is input through the terminal by the user) once counting the number of lines in the file. Then after, I had to create an array of objects from the file, of the correct size (where the num of lines comes in). Then I had to create another scanner for the file and read through it again, storing it in the array I created. And lastly, had to return the array in the method.
My problem is I cannot seem to get the second scanner to actually store the file objects in the array.
I've tried using .nextLine inside a for loop that also calls the array, but it doesn't seem to be working.
public static Data[] getData(String filename) {
Scanner input = new Scanner(new File(filename));
int count = 0;
while (input.hasNextLine()) {
input.nextLine();
count++;
}
System.out.println(count);
Data[] data = new Data[count];
Scanner input1 = new Scanner(new File(filename));
while (input1.hasNextLine()) {
for (int i = 0; i < count; i++) {
System.out.println(data[i].nextLine);
}
}
return data;
}
I expect the output to successfully read the input file so that it can be accessed by other methods that I have created (not shown).
You should definitely use an IDE if you don't have one, try intellij... There you have autocompletion and syntax checking and much more.
It is not clear what you want to do in your for loop, because there are several mistakes, for example the readline() function works only with the scanner objekt, so you can do input.nextline() or input1.nextline()`...
so I just show you, how you can get the Data from a file with Scanner:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Readfile {
public static void getData(String filename) throws FileNotFoundException {
ArrayList<String> test = new ArrayList<>(); //arraylist to store the data
Scanner inputSc = new Scanner(new File(filename)); //scanner of the file
while (inputSc.hasNextLine()) {
String str = inputSc.nextLine();
System.out.println(str); //print the line which was read from the file
test.add(str); //adds the line to the arraylist
//for you it would be something like data[i] = str; and i is a counter
}
inputSc.close();
}
public static void main(String[] args) {
try {
getData("/home/user/documents/bla.txt"); //path to file
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You don't need to read thru the file twice - just use an ArrayList to hold the data that's coming in from the file, like this, and then return Data[] at the end:
public static Data[] getData(String filename) {
List<Data> result = new ArrayList<>();
try (Scanner input = new Scanner(new File(filename))){
while (input.hasNextLine()) {
Data data = new Data(input.nextLine());
result.add(data);
}
}
return result.toArray(new Data[0]);
}
Not clear what Data.class do you mean, if you switch it to String, the problem obviously would be in this line
System.out.println(data[i].nextLine);
if you want to assign and print simultaneously write this
for (int i = 0; i < count; i++) {
data[i] = input1.next();
System.out.println(data[i]);
}
and dont forget to close your Scanners, better use try-with-resources.
If your Data is your custom class you'd better learn about Serialization-Deserialization
Or use some ObjectMapper-s(Jackson, for example) to store your class instances and restore them.
Your way of opening the file just to count the lines and then again looping through its lines to store them in the array is not that efficient, but it could be just a school assignment.
Try this:
public static Data[] getData(String filename) {
Scanner input = null;
try {
input = new Scanner(new File(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
int count = 0;
while (input.hasNextLine()) {
input.nextLine();
count++;
}
input.close();
System.out.println(count);
Data[] data = new Data[count];
try {
input = new Scanner(new File(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
for (int i = 0; i < count; i++) {
Data d = new Data(input.nextLine(), 0, 0);
data[i] = d;
System.out.println(data[i].name);
}
input.close();
return data;
}
After the 1st loop you must close the Scanner and reopen it so to start all over from the first line of the file.

How to print multiple lines from text files in Java?

I have a text file that contains three lines of code.
That is,
Hello.
How may I help you?
What can I do for you today?
I tried printing the first line and it worked.Now I want to print the rest of the lines in the console but it's only displaying first line 4 times like this.
Hello.
Hello.
Hello.
Hello.
Below is the code that I am trying to run and the file is in root folder.
public class Test
{
public static void main(String[] args)
{
int counter = 0;
/*open the file */
BufferedReader reader = null;
String greeting = null;
int rand;
File file = new File("Greetings.txt");
try
{
reader = new BufferedReader(new FileReader(file));
/*read the file*/
String greetingPicker = null;
/*single greeting*/
/*greeting = greetingPicker;*/
List<String> listOfGreetings = new ArrayList<String>();
while ((greetingPicker = reader.readLine()) != null)
{
listOfGreetings.add(greetingPicker);
}
reader.close();
rand = (int) Math.random() * (listOfGreetings.size()) + 1;
greeting = listOfGreetings.get(rand - 1);
for (int i = 0; i < listOfGreetings.size(); i++)
{
System.out.println(listOfGreetings.get(counter));
}
} catch (Exception e)
{
System.out.println("File cannot be found!!");
}
}
}
You are getting the value for the wrong index: You mistakenly used counter instead of i in your loop. Change this
for(int i=0; i < listOfGreetings.size(); i++){
System.out.println(listOfGreetings.get(counter));
}
to this:
for(int i=0; i < listOfGreetings.size(); i++){
System.out.println(listOfGreetings.get(i));
}
By the way, you are using Math.random() and it is instantly converted to a int, because you forgot to add correct parentheses, so change this
rand = (int) Math.random() * (listOfGreetings.size()) + 1;
to this:
rand = (int) (Math.random() * (listOfGreetings.size()) + 1);
You dont need your counter, use i ! ;)
for(int i=0; i < listOfGreetings.size();i++){
System.out.println(listOfGreetings.get(i));
}
Just change
System.out.println(listOfGreetings.get(counter));
by
System.out.println(listOfGreetings.get(i));
You forgot to change the counter.
You don't need to use counter, and put close in the end like this:
for(int i=0; i < listOfGreetings.size();i++){
System.out.println(listOfGreetings.get(i));
}
reader.close();
The "counter" variable here is not being incremented:
for(int i=0; i < listOfGreetings.size();i++){
System.out.println(listOfGreetings.get(counter));
}
You should change it to "i" instead:
for(int i=0; i < listOfGreetings.size();i++){
System.out.println(listOfGreetings.get(i));
}
Try using the chunk below. It's simpler and works perfectly.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class FileReader{
public static void main(String[] args){
//define file path
String stringFileToRead = "Greetings.txt";
//the file
File stringFile = new File(stringFileToRead);
//Scanner object to take input from the file
Scanner fileToRead = null;
try{
//Read the file
fileToRead = new Scanner(stringFile);
}
//catch exception
catch (Exception e){
System.out.println("Unable to open file.");
System.exit(0);
}
//print the content of the file
System.out.println("The file contains the following contents:\n");
int lineNum = 1;
while(fileToRead.hasNextLine()){
String line = fileToRead.nextLine();
System.out.println("Line "+lineNum+": "+line);
lineNum++;
}
}
}

How to find smallest value(from values given in a txt file) using BufferedReader in java

I have been given this question for practice and am kind of stuck on how to complete it. It basically asks us to create a program which uses a BufferedReader object to read values(55, 96, 88, 32) given in a txt file (say "s.txt") and then return the smallest value of the given values.
So far I have got two parts of the program but i'm not sure how to join them together.
import java.io.*;
class CalculateMin
{
public static void main(String[] args)
{
try {
BufferedReader br = new BufferedReader(new FileReader("grades.txt"));
int numberOfLines = 5;
String[] textInfo = new String[numberOfLines];
for (int i = 0; i < numberOfLines; i++) {
textInfo[i] = br.readLine();
}
br.close();
} catch (IOException ie) {
}
}
}
and then I have the loop which I made but i'm not sure how to implement it into the program above. Eugh I know i'm complicating things.
int[] numArray;
numArray = new int[Integer.parseInt(br.readLine())];
int smallestSoFar = numArray[0];
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] < smallestSoFar) {
smallestSoFar = numArray[i];
}
}
Appreciate your help
Try this code, it iterates through the entire file comparing number from each line with the previously read lowest number-
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("grades.txt"));
String line;
int lowestNumber = Integer.MAX_VALUE;
int number;
while ((line = br.readLine()) != null) {
try {
number = Integer.parseInt(line);
lowestNumber = number < lowestNumber ? number : lowestNumber;
} catch (NumberFormatException ex) {
// print the error saying that the line does not contain a number
}
}
br.close();
System.out.println("Lowest number is " + lowestNumber);
} catch (IOException ie) {
// print the exception
}
}

error while getting data from file to array

I'm trying to get saved data in a text file to an array to use it in my code and then search this array for a string submitted from the user from the GUI , but for some reason I print out the data in the array it is all null. here's the code !!
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class IO {
File f = new File("DB.txt");
PrintWriter write;
Scanner input;
String[][] data;
String nameToSearch;
// search constructor
public IO(String name) {
super();
nameToSearch = name;
try {
input = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println("File not found please restart the program");
}
data = new String[linesCounter()][2];
int i = 0;
while (input.hasNext()) {
data[i][0] = input.nextLine();
data[i][1] = input.nextLine();
i++;
}
}
public IO(String name, String number) {
try {
write = new PrintWriter(new FileWriter(f, true));
} catch (IOException e) {
System.out.println("Error");
}
write.println(name);
write.println(number);
write.close();
}
int linesCounter() {
try {
input = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println("File not found please restart the program");
}
int counter = 0;
while (input.hasNext()) {
input.nextLine();
counter++;
}
return counter / 2;
}
int contactFinder() {
int i = 0;
while (input.hasNext()) {
if (data[i][0].equalsIgnoreCase(nameToSearch))
return i;
i++;
}
return -1;
}
String nameGetter() {
return data[contactFinder()][0];
}
String numGetter() {
return data[contactFinder()][1];
}
}
It looks like you read all the lines in from the file to count how many lines there are, and then when you go to read the data, you're starting from where you left off, which would be the end of the file.
It's also worth noting that you can use commons-io FileUtils to easily read all the lines from a file.
For example:
List<String> lines = FileUtils.readLines(f);
String[][] data = new String[lines.length][2];
for (int i = 0; i < lines.size(); i++) {
data[i][i % 2] = lines.get(i);
}
If you also don't want to use a (very useful) third party library, you could load up the data pretty simply with:
List<String> lines = new ArrayList<String>();
Scanner input = new Scanner(f);
while (input.hasNextLine()) {
lines.add(input.nextLine());
}
input.close();
Then go into the array population.
I would advice you to use RandomAccessFile. This has methods such as readLine() to read the line and seek(long pos) to set the file read pointer. You may use seek(0L) to restart the reading of the file.

reading line and splitting to char array

I can't understand why my program not functioning. It compiles but nothing is printed. I have a 5 character word in file. I need to read line from that file and then split it into char array, which I then want print out.Thanks!
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedReader;
public class test {
public static void main(String[] args)
{
BufferedReader line = null;
char[] array = new char[7];
try{
line = new BufferedReader(new FileReader(args[0]));
String currentLine;
while((currentLine = line.readLine()) != null)
{
array = currentLine.toCharArray();
}
for(int i = 0; i < array.length; i++)
{
System.out.print(array[i]);
}
}//try
catch(IOException exception)
{
System.err.println(exception);
}//catch
finally
{
try
{
if(line != null)
line.close();
}//try
catch(IOException exception)
{
System.err.println("error!" + exception);
}//catch
}//finally
} // main
} // test
Your while loop skips every line except the last one so it could be possible that your last line is empty. To display every line you could have:
while ((currentLine = line.readLine()) != null) {
array = currentLine.toCharArray();
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
System.out.println();
}
Or if you just have the 1 line, You could simply use:
String currentLine = line.readLine();
...
Your program prints only last line
You have to Print in loop.
while (....!=null)
{
array = currentLine.toCharArray();
for(int i = 0; i < array.length; i++)
{
System.out.print(array[i]);
}
}
If above was not a problem than check your file permission.
Check your system may be program is not able to read from file due to permission on file.

Categories

Resources