Trying to fill a two dimensional ArrayList from txt file - java

This is supposed to be a Sudoku Puzzle solver and it is required I use a two dimensional ArrayList for the puzzle.
I'm trying to fill an ArrayList using numbers from a txt file. The code in my test class can make a 9x9 ArrayList and fill it with numbers 1-9 using the loop I made to test how filling a two dimensional ArrayList works.
import java.util.*;
import java.io.*;
public class test
{
public static void main(String args[])
{
ArrayList<ArrayList<Integer>> data = new ArrayList<ArrayList<Integer>>();
//Loop to add 9 rows
for(int i=1; i<=9; i++)
{
data.add(new ArrayList<Integer>());
}
//Loop to fill the 9 rows with 1-9
for(int k=0; k<9; k++)
{
for(int j=1; j<=9; j++)
{
data.get(k).add(j);
}
}
//Loop to print out the 9 rows
for(int r=0; r<9; r++)
{
System.out.println("Row "+(r+1)+data.get(r));
}
//Reads the file. Need to use this to set the array
File file = new File("F:\\Data Structures 244\\FINAL PROJECT\\SudokuSolver\\sudoku.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
My problem comes when I try to take the numbers I have stored in the txt file and use them to fill the ArrayList in the order they are read. I tried this code so that it would read the number from the txt file and place it into the ArrayList by having it repeat so it would do the first 9 numbers from the txt file into the first row of the ArrayList and then go to the next row in the txt file as well as the ArrayList to fill those numbers.
File file = new File("F:/Data Structures 244/FINAL PROJECT/SudokuSolver/sudoku.txt");
//Needs this try and catch
try {
Scanner solutionFile = new Scanner(file);
int cell=0;
while (solutionFile.hasNextInt())
{
//Loop to fill the 9 rows with the numbers from the sudoku.txt
for(int k=0; k<9; k++)
{
for(int j=1; j<=9; j++)
{
cell = solutionFile.nextInt();
data.get(k).add(cell);
}
}
}
solutionFile.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
for(int r=0; r<9; r++)
{
System.out.println("Row "+(r+1)+data.get(r));
}
I get an Exception in thread "main" java.util.NoSuchElementException
with this line cell = solutionFile.nextInt();
This is the sudoku.txt file
346791528
918524637
572836914
163257489
895143762
427689351
239415876
684372195
751968243
I tried it like that at first and get that error but then I try taking all of the numbers and putting them on one line so my for loops will only read them 9 numbers at a time but when I test to print the ArrayList or what should be in it after it adds them the entire ArrayList is blank.
What is the problem with it not reading the numbers from the file and putting them into the ArrayList so it will print?

An integer can be more than one character. You're reading the entire line as a single number and then failing after you finish the nine reads (1 for each line).
You can reformat your text file so that the numbers are broken up: (I believe a space will work if not a new line definitely will)
so like
3 4 6 7 9 1 5 2 8
...
Or you can read the whole number and parse it yourself
int temp = solutionFile.nextInt();
for(int i = 8; i > 0; i--) {
int cell = temp / (10 * i);
data.get(k).add(cell);
}
//add the last cell
int cell = temp % 10;
data.get(k).add(cell);
Or you could read the value as a string and parse it
String line = solutionFile.next();
for(int i = 0; i < line.length; i++) {
Integer cell = Integer.parseInt(line.substring(i, i+1));
data.get(k).add(cell);
}
This isn't a valid way to print a list of numbers (ArrayList's toString doesn't print the list for you you have to do it manually)
for(int r=0; r<9; r++)
{
System.out.println("Row "+(r+1)+data.get(r));
}
Should be something like
for(int r = 0; r < data.size(); r++)
{
System.out.print("Row " + (r+1) + ": ");
for(Integer num : data.get(r)) {
System.out.print(num + " ");
}
System.out.println(); //to end the line
}

Related

How to create an array from the contents of a text file to be sorted?

This is a program that takes these three arrays and sorts them using insertion sort and counting the number of comparisons and swaps performed for each array when sorted.
I'm now trying to test three other arrays that have been made on text files. The these three text files are just lists of numbers, the first text file is called "array4.txt" and its list of numbers contains 1 through 2000 in order.
The second file is called "array5.txt" and its list of numbers contains 2000 through 1 in descending order. Lastly, the third file is called "array6.txt" and its list of numbers contains a list of randomly mixed numbers from 1 to 2000, including 1 and 2000 with no repeats.
My goal is to read these files and put their values into an actual array and for my insertion sort method to read them, sort them, and count the number of comparisons and exchanges just as what I did with my first three arrays.
I'm very new to Java and don't know exactly how to do this.
import java.util.Scanner;
import java.io.*;
public class InsertionSort
{
public static void main(String args[]) throws IOException
{
int[] Array = {1,2,3,4,5,6,7,8,9,10};
int[] Array2 = {10,9,8,7,6,5,4,3,2,1};
int[] Array3 = {1,10,2,9,3,8,4,7,5,6};
System.out.println("Insertion Sort: ");
System.out.println();
System.out.println("Best Case Scenario: ");
printArray(Array);
insertionSort(Array);
System.out.println("Worst Case Scenario: ");
printArray(Array2);
insertionSort(Array2);
System.out.println("Average Case Scenario: ");
printArray(Array3);
insertionSort(Array3);
}
public static void insertionSort(int[] list)
{
int comps = 0, swaps = 0;
for(int i = 1; i < list .length; i++) {
int j = i;
// compare i with sorted elements and insert it
// sorted elements: [0..i-1]
while (j > 0 && list[j] < list[j - 1]) {
int temp = list[j];
list[j] = list[j - 1];
list[j - 1] = temp;
swaps++;
comps++; // loop condition true
j--;
}
comps++; // checking loop condition when false
}
//printArray(list);
System.out.println("Comparisons: " + comps
+ " Swaps: " + swaps);
System.out.println();
}
static void printArray(int[] array){
for(int i=0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
System.out.println();
}
}
This is what I came up with. Hope it helps!
package com.company;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
// Replace array.txt with the name of your txt file and your path
Scanner fileScanner = new Scanner(new File("array.txt"));
// Counter variable so we'll know the size of the array we'll need
int counter = 0;
// Iterate through the file counting the number of integers and incrementing the counter variable
while(fileScanner.hasNextInt()){
counter++;
fileScanner.nextInt();
}
// Reset the scanner to the beginning of the txt file
fileScanner = new Scanner(new File("array.txt"));
// Scan each integer into the array
int [] array = new int[counter];
for (int i = 0; i < array.length; ++i) array[i] = fileScanner.nextInt();
}
}
Here you go:
public void getIt() {
List<Integer> ints = new ArrayList(); //temporary holder
try (Scanner scanner = new Scanner("filename.txt")) { //open a scanner that will scan our file
scanner.forEachRemaining(line -> { //iterate through each line in our file
String[] numberStrings = line.split(","); // the comma is your presumed delimeter IF one exists
for (int x = 0; x < numberStrings.length; x++) { // loop through each item separated by a comma on each line
ints.add(Integer.parseInt(numberStrings[x])); // turn this string into an int and add it to your list
}
});
}
Integer[] integerArray = ints.toArray(new Integer[ints.size()]); //transform our list into an array
}
If it's only one number per line you don't need the for loop or the line.split inside of the forEachRemaining

Filling a 2d character array from a file in java

I'm a beginner in java and I am trying to fill a 2d character array from an input file. To do this I constructed a method which takes in a 2d character array as a parameter variable, then reads the file and stores it as a character array. So far I have done everything except fill the array, as when I run the code the program throws a NoSuchElement exception. If anyone could help me with this I would greatly appreciate it.
public static char [][] MakeWordArray (char [][] givenArray)
{
try
{
File wordFile= new File ("words.txt");
Scanner in= new Scanner (wordFile);
int rows =0;
int col=0;
while (in.hasNextLine())
{
rows = rows + 1;
col = col + 1;
in.next();
}
char [][] words = new char [rows][col];
File wordFile2= new File ("words.txt");
Scanner in2= new Scanner(wordFile2);
for ( int i = 0; i < rows; i++)
{
for (int j = 0; j < col; j++)
{
String wordly = in2.nextLine();
words [i][j] = wordly.charAt(i);
}
}
return words;
}
catch (FileNotFoundException e)
{
System.out.println("File Does Not Exist");
}
return null;
}
I think your counting methods have some problems.
If you want to count how many lines your .txt have:
int counter = 0;
while (in.hasNextLine())
{
counter++;
in.nextLine();
}
If you want to count how many char your .txt have:
int counterWithoutSpace = 0, counterWithSpace = 0;
while (in.hasNextLine())
{
String line = in.nextLine();
Scanner inLine = new Scanner(line);
while (inLine.hasNext())
{
String nextWord = inLine.next();
counterWithoutSpace += nextWord.length();
counterWithSpace += nextWord.length() + 1;
}
counterWithSpace--;
}
If you want to count how many char you have on each line, I recommend ArrayList. Because the size of your array is dynamic.
Note that you can also you can use the char counter logic above with List too.See as follows:
List<Integer> arr = new ArrayList<Integer>();
while (in.hasNextLine())
{
arr.add(in.nextLine().length());
}
And if you realy needs the static array, you can use:
Integer[] intArr = arr.toArray(new Integer[0]);
You can transform its entire function as below to get a list of every Character of the .txt:
List<Character> arr = new ArrayList<Character>();
while (in.hasNextLine())
{
String line = in.nextLine();
for (char c : line.toCharArray())
{
arr.add(c);
}
}
Try using a do while loop instead of the while
do
{
rows=rows+1;
col=lol+1;
in.next();
}
while(in.hasNext());
There are multiple questions here.
1) Why did you provide a char[][] parameter when you are not even using it?
2) Why are you using two files when all you need to do is read from a file and convert it in 2d Array?
3) The method name should follow camel casing convention.
From what i understood from your question, This is a code i've tried.
NOTE- because the requirement is of an Array and not dynamic datatypes like List ArrayList etc., the data entered into char array might be lost
Saying that here is what works.
public class StackOverflow{
public static char [][] makeWordArray ()
{
try{
File f = new File("C:\\docs\\mytextfile.txt");
Scanner scan = new Scanner(f);
int row = 0, col = 0;
String readData = "";
while(scan.hasNextLine()){
readData += scan.nextLine();
row++;
}
double range = (readData.length()/row);
col = (int)Math.ceil(range);
char[][] arr = new char[row][col];
int count = 0;
for (int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
arr[i][j] = readData.charAt(count++);
System.out.println("Pos: ["+ i +"][" + j + "]" + arr[i][j]);
}
}
return arr;
}
catch(FileNotFoundException fe){
System.err.println(fe.getMessage());
return null;
}
}
public static void main(String[] arg){
char[][] myarr = StackOverflow.makeWordArray();
//print your array
}
}

2D array integer column in descending order [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am having trouble with "//Clinton's delegates in order from highest to lowest". I realize that it's currently in ascending order (I was more familiar with this), but it still isn't looping enough times to even do the ascending order properly. I would like for the third column to be in descending order --> Integer.parseInt(primary[row][2]).
import java.io.*;
public static void main(String[] args) throws IOException
{
//Read text file
FileReader fr = new FileReader("primary1.txt");
BufferedReader br = new BufferedReader(fr);
//2D array
String[][] primary = new String[44][5];
//Section break
System.out.println("1. The file contents are:\n");
//Add column titles
System.out.println("States\t\t\t\tCandidate#1\tVotes\t\tCandidate#2\tVotes");
//Set delimiter as "/"
String line;
int i=0;
while((line=br.readLine())!=null){
primary[i]=line.split("/");
i++;
}
//Print text file
for(int row=0; row<primary.length; row++){
for(int col=0; col<primary[row].length; col++){
//Add space between columns
System.out.print(primary[row][col] + "\t\t");
}
//Newline
System.out.println("");
}
//Clinton's delegates in order from highest to lowest
int temp=0;
for(int row=0; row<primary.length-1; row++){
//Parse Integer
int delC = Integer.parseInt(primary[row][2]);
int delC1 = Integer.parseInt(primary[row+1][2]);
if(delC > delC1){
temp=delC1;
delC1=delC;
delC=temp;
}
System.out.println(temp);
}
}
Try this:
public static void main(String[] args) throws IOException {
//Read text file
FileReader fr = new FileReader("primary1.txt");
BufferedReader br = new BufferedReader(fr);
//2D array
String[][] primary = new String[44][5];
//Section break
System.out.println("1. The file contents are:\n");
//Add column titles
System.out.println("States\t\t\t\tCandidate#1\tVotes\t\tCandidate#2\tVotes");
//Set delimiter as "/"
String line;
int i=0;
while((line=br.readLine())!=null){
primary[i]=line.split("/");
i++;
}
//Print text file
for(int row=0; row<primary.length; row++){
for(int col=0; col<primary[row].length; col++){
//Add space between columns
System.out.print(primary[row][col] + "\t\t");
}
//Newline
System.out.println();
}
//Clinton's delegates in order from highest to lowest
for(int row=0; row<primary.length-1; row++){
for(int row1=row+1; row1<primary.length; row1++) {
//Parse Integer
int delC = Integer.parseInt(primary[row][2]);
int delC1 = Integer.parseInt(primary[row1][2]);
if(delC < delC1){
String[]tmpprimary = primary[row];
primary[row] = primary[row1];
primary[row1] = tmpprimary;
}
}
}
System.out.println("\n**************************** Order Descending *******************************");
System.out.println("States\t\t\t\tCandidate#1\tVotes\t\tCandidate#2\tVotes");
for(int row=0; row<primary.length; row++){
for(int col=0; col<primary[row].length; col++){
//Add space between columns
System.out.print(primary[row][col] + "\t\t");
}
//Newline
System.out.println();
}
}
I think your code looks like trying to do bubble sort. If that is what you are trying to do then you need to have 2 for loops to iterate the contents and swap them. Since you are using String array hence the array elements needs to be swapped. not just numbers in the array for display. See the following modified code.
I see you have tagged with selection sort. Let me know if you need that. Bubble sort below because your looked like doing that.
public static void main(String[] args) throws IOException {
// Read text file
FileReader fr = new FileReader("primary1.txt");
BufferedReader br = new BufferedReader(fr);
// 2D array
String[][] primary = new String[44][5];
// Section break
System.out.println("1. The file contents are:\n");
// Add column titles
System.out.println("States\t\t\t\tCandidate#1\tVotes\t\tCandidate#2\tVotes");
// Set delimiter as "/"
String line;
int i = 0;
while ((line = br.readLine()) != null) {
primary[i] = line.split("/");
i++;
}
// Print text file
for (int row = 0; row < primary.length; row++) {
for (int col = 0; col < primary[row].length; col++) {
// Add space between columns
System.out.print(primary[row][col] + "\t\t");
}
// Newline
System.out.println("");
}
// Clinton's delegates in order from highest to lowest
int temp = 0;
// bubble sort
for (int row = 0; row < primary.length - 1; row++) {
for (int k = row + 1; k < primary.length; k++) {
// Parse Integer
int delC = Integer.parseInt(primary[row][2]);
int delC1 = Integer.parseInt(primary[k][2]);
int delO = Integer.parseInt(primary[row][4]);
if (delC >= delC1) {
// swap contents
swap(primary, row, k);
temp = delC1;
delC1 = delC;
delC = temp;
}
}
// System.out.println(temp);
}
// Print output
for (int row = 0; row < primary.length; row++) {
System.out.println(primary[row][2]);
}
}
private static void swap(String[][] primary, int row, int k) {
String[] temp = primary[k];
primary[k] = primary[row];
primary[row] = temp;
}

Printing out a .txt file

I have a quick question I have a program I am writing in java, it takes a .txt file reads what is inside it(this case it being a bunch of numbers) the program stores it in an array, then it sorts it from least to greatest it also finds the average as well as it tells me how many numbers in the array are bigger than the average. I have managed to do all of that but what I am having trouble with is now I want the program to print out another .txt file but this time with the results of my program. I want it to print out the sorted array the average the number of how many elements are in the array as well as the number of numbers bigger than the average. here is my code that i have:
import java.util.Scanner;
import java.util.Arrays;
class numberSorter{
public static void main (String[]args)throws Exception{
//calling the .txt file
java.io.File file= new java.io.File("numTestData.txt");
java.io.File file2=new java.io.File("dataOut.txt");
Scanner input = new Scanner(file);
//getting the numbers from the file
int num=input.nextInt();
//starting variables
int ct=0;
int bigger=0;
double average;
double track=0;
double[]numberArray=new double[num];
//filling in the rest of the numbers in the array
for(int i =0; i < numberArray.length; i++){
numberArray[i] = input.nextInt();
}
input.close();
//calling the sort method to sort the array
sort(numberArray);
//tracking how many elements are in the array
for(int i=0;i<numberArray.length;i++){
track+=numberArray[i];
}
//finding the average of the sorted array
average=track/numberArray.length;
//looking through the array to find which number is bigger than the average
for(int i=0;i<numberArray.length;i++)
{
if(numberArray[i]>average)
bigger++;
}
//checking to see of the .txt file exists
if(file2.exists()){
System.out.println("file exists");
System.exit(0);
}
//creating a file
try(
java.io.PrintWriter output=new java.io.PrintWriter(file2);
){
//printing out to the .txt file
output.println("Number of slots:");
output.println(numberArray.length);
output.println("sorted:");
for(int i =0; i < numberArray.length; i++){
output.println(numberArray[i]);
}
output.println("Average:");
output.println(average);
output.println("number of above average values: ");
output.println(bigger);
}
}
//sort method
public static void sort(double[]arrange)
{
//looking for the smallest number
for(int i=0;i<arrange.length-1;i++){
double currentMin=arrange[i];
int currentMinIndex=i;
//checking to see if the current number is smaller or bigger
for(int j=i+1;j<arrange.length;j++){
if(currentMin>arrange[j]){
currentMin=arrange[j];
currentMinIndex=j;
}
}
//will arrange the numbers if current number is not smaller
if(currentMinIndex!=i){
arrange[currentMinIndex]=arrange[i];
arrange[i]=currentMin;
}
}
}
}
Now my question is i keep getting this error, everything complies but when I try to run it i come across this:
----jGRASP exec: java numberSorter
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at numberSorter.main(numberSorter.java:26)
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
Ive tried to mees around with the code but I still keep getting this any help please? I am still learning java
To get rid of errors related to a not matching int in the first line, i would recommend not using this first int counting the numbers, you want to parse.
So your input file would be:
12345 23456 123 4567 123456 7654 999 3453 997733 43 654321
You could use an ArrayList instead of an array and then go through the file with input.hasNext().
I updated the parts in your code:
import java.util.ArrayList;
import java.util.Scanner;
public class NumberSorter {
public static void main(String[] args) throws Exception {
// calling the .txt file
java.io.File file = new java.io.File("numTestData.txt");
java.io.File file2 = new java.io.File("dataOut.txt");
Scanner input = new Scanner(file);
int bigger = 0;
double average;
double track = 0;
ArrayList<Double> numberArray = new ArrayList<Double>();
while (input.hasNext()) {
numberArray.add(input.nextDouble());
}
input.close();
// calling the sort method to sort the array
sort(numberArray);
// tracking how many elements are in the array
for (int i = 0; i < numberArray.size(); i++) {
track += numberArray.get(i);
}
// finding the average of the sorted array
average = track / numberArray.size();
// looking through the array to find which number is bigger than the
// average
for (int i = 0; i < numberArray.size(); i++) {
if (numberArray.get(i) > average)
bigger++;
}
// checking to see of the .txt file exists
if (file2.exists()) {
System.out.println("file exists");
System.exit(0);
}
// creating a file
try (java.io.PrintWriter output = new java.io.PrintWriter(file2);) {
// printing out to the .txt file
output.println("Number of slots:");
output.println(numberArray.size());
output.println("sorted:");
for (int i = 0; i < numberArray.size(); i++) {
output.println(numberArray.get(i));
}
output.println("Average:");
output.println(average);
output.println("number of above average values: ");
output.println(bigger);
}
}
// sort method
public static void sort(ArrayList<Double> arrange) {
// looking for the smallest number
for (int i = 0; i < arrange.size() - 1; i++) {
double currentMin = arrange.get(i);
int currentMinIndex = i;
// checking to see if the current number is smaller or bigger
for (int j = i + 1; j < arrange.size(); j++) {
if (currentMin > arrange.get(j)) {
currentMin = arrange.get(j);
currentMinIndex = j;
}
}
// will arrange the numbers if current number is not smaller
if (currentMinIndex != i) {
arrange.set(currentMinIndex, arrange.get(i));
arrange.set(i,currentMin);
}
}
}
}

Reading 2-D array from a file

I have a 2-D int array in file 'array.txt'. I am trying to read all the elements in the file in a two dimensional array. I am having problem in copying. It shows all the elements having value '0' after copying instead their original value. Please help me.
My code is :
import java.util.*;
import java.lang.*;
import java.io.*;
public class appMainNineSix {
/**
* #param args
*/
public static void main(String[] args)
throws java.io.FileNotFoundException{
// TODO Auto-generated method stub
Scanner input = new Scanner (new File("src/array.txt"));
int m = 3;
int n = 5;
int[][] a = new int [m][n];
while (input.next()!=null){
for (int i=0;i<m;i++){
for (int j=0;j<n;j++)
a[i][j]= input.nextInt();
}
}
//print the input matrix
System.out.println("The input sorted matrix is : ");
for(int i=0;i<m;i++){
for(int j=0;j<n;j++)
System.out.println(a[i][j]);
}
}
}
while (input.next()!=null)
This will consume something from the scanner input stream. Instead, try using while (input.hasNextInt())
Depending on how robust you want your code to be, you should also check inside the for loop that something is available to be read.
Scanner input = new Scanner (new File("src/array.txt"));
// pre-read in the number of rows/columns
int rows = 0;
int columns = 0;
while(input.hasNextLine())
{
++rows;
Scanner colReader = new Scanner(input.nextLine());
while(colReader.hasNextInt())
{
++columns;
}
}
int[][] a = new int[rows][columns];
input.close();
// read in the data
input = new Scanner(new File("src/array.txt"));
for(int i = 0; i &lt rows; ++i)
{
for(int j = 0; j &lt columns; ++j)
{
if(input.hasNextInt())
{
a[i][j] = input.nextInt();
}
}
}
An alternative using ArrayLists (no pre-reading required):
// read in the data
ArrayList&ltArrayList&ltInteger&gt&gt a = new ArrayList&ltArrayList&ltInteger&gt&gt();
Scanner input = new Scanner(new File("src/array.txt"));
while(input.hasNextLine())
{
Scanner colReader = new Scanner(input.nextLine());
ArrayList col = new ArrayList();
while(colReader.hasNextInt())
{
col.add(colReader.nextInt());
}
a.add(col);
}
The problem is when u reach the end of the file it throughs an exception that no usch element exist.
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Scanner input = new Scanner(new File("array.txt"));
int m = 3;
int n = 5;
int[][] a = new int[m][n];
while (input.hasNextLine()) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
try{// System.out.println("number is ");
a[i][j] = input.nextInt();
System.out.println("number is "+ a[i][j]);
}
catch (java.util.NoSuchElementException e) {
// e.printStackTrace();
}
}
} //print the input matrix
System.out.println("The input sorted matrix is : ");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.println(a[i][j]);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
I knew that making catch without processing the exception but it temporary works.
Please be aware I put the file outside the source folder.
Well the problem may be that you've got that pair of nested loops to read the numbers stuck inside that while loop. Why would you want to re-read the array values after you've read them once? And note that if there's anything in the file after the last number, then you'll fill the array in with whatever .nextInt() returns after end-of-file has been reached!
edit — well .nextInt() should throw an exception I guess when input runs out, so that may not be the problem.
Start simple...
change:
for (int j=0;j<n;j++)
a[i][j]= input.nextInt();
to:
for (int j=0;j<n;j++)
{
int value;
value = input.nextInt();
a[i][j] = value;
System.out.println("value[" + i + "][" + j + " = " + value);
}
And make sure that the values are read in.
Also, you should not call next without first calling (and checking) hasNext (or nextInt/hasNextInt).
You can try Using Guava ,
public class MatrixFile {
private final int[][] matrix;
public MatrixFile(String filepath) {
// since we don't know how many rows there is going to be, we will
// create a list to hold dynamic arrays instead
List<int[]> dynamicMatrix = Lists.newArrayList();
try {
// use Guava to read file from resources folder
String content = Resources.toString(
Resources.getResource(filepath),
Charsets.UTF_8
);
Arrays.stream(content.split("\n"))
.forEach(line -> {
dynamicMatrix.add(
Arrays.stream(line.split(" "))
.mapToInt(Integer::parseInt)
.toArray()
);
});
} catch (IOException e) {
// in case of error, always log error!
System.err.println("MatrixFile has trouble reading file");
e.printStackTrace();
}
matrix = dynamicMatrix.stream().toArray(int[][]::new);
}

Categories

Resources