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 < rows; ++i)
{
for(int j = 0; j < columns; ++j)
{
if(input.hasNextInt())
{
a[i][j] = input.nextInt();
}
}
}
An alternative using ArrayLists (no pre-reading required):
// read in the data
ArrayList<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>();
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);
}
Related
This code takes two txt files, reads them puts them in 2d arrays and should check if the numbers in the files are magic squares but it keeps returning NumberFormatException error. I'm new to java so if anyone could help me that would be great. I'm pretty sure the problem come from the txt file being string and the 2d array needing to be in int form. But how and where do I make that conversion on my code?
this is what i have:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class ms {
public static void main(String[] args) throws FileNotFoundException {
String filename1 = "magicSquaresData.txt", filename2 = "magicSquaresData.txt";
int nos[][] = null;
nos = getArray(filename1);
boolean b = isMagicSquare(nos);
printArray(nos);
if (b) {
System.out.println("It is a magic Square");
} else {
System.out.println("It is not a magic Square");
}
System.out.println("\n");
nos = getArray(filename2);
b = isMagicSquare(nos);
printArray(nos);
if (b) {
System.out.println("It is a magic Square");
} else {
System.out.println("It is not a magic Square");
}
}
private static int[][] getArray(String filename) throws FileNotFoundException {
String line;
int nos[][] = null;
int size = 0, rows = 0;
Scanner sc = null;
try {
sc = new Scanner(new File(filename));
while (sc.hasNext()) {
if (!sc.nextLine().isEmpty())
size++;
}
sc.close();
nos = new int[size][size];
sc = new Scanner(new File(filename));
while (sc.hasNext()) {
line = sc.nextLine();
if (!line.isEmpty()) {
String arr[] = line.split("\t");
for (int i = 0; i < arr.length; i++) {
nos[rows][i] = Integer.valueOf(arr[i]);
}
rows++;
}
}
sc.close();
} catch (FileNotFoundException e) {
System.out.println(e);
}
return nos;
}
private static void printArray(int[][] nos){
for(int i = 0; i<nos[0].length;i++) {
for (int j = 0; j < nos[0].length; j++){
System.out.printf("%-3d",nos[i][j]);
}
System.out.println();
}
}
private static boolean isMagicSquare(int[][] square) {
boolean bool = true;
int order = square.length;
int[] sumRow = new int[order];
int[] sumCol = new int[order];
int[] sumDiag = new int[2];
Arrays.fill(sumRow, 0);
Arrays.fill(sumCol, 0);
Arrays.fill(sumDiag, 0);
for (int row = 0; row < order; row++){
for (int col = 0; col < order; col++) {
sumRow[row] += square[row][col];
}
}
for (int col = 0; col < order; col++) {
for (int row = 0; row < order; row++) {
sumCol[col] += square[row][col];
}
}
for (int row = 0; row < order; row++) {
sumDiag[0] += square[row][row];
}
for (int row = 0; row < order; row++) {
sumDiag[1] += square[row][order - 1 - row];
}
bool = true;
int sum = sumRow[0];
for (int i = 1; i < order; i++) {
bool = bool && (sum == sumRow[i]);
}
for (int i = 0; i < order; i++) {
bool = bool && (sum == sumCol[i]);
}
for (int i = 0; i < 2; i++) {
bool = bool && (sum == sumDiag[i]);
}
return bool;
}
}
SUGGESTION:
Substitute nos[rows][i] = Integer.valueOf(arr[i]); for a custom method that will tell you WHERE the error is occurring.
EXAMPLE:
public static Integer tryParse(String text, int row, int i) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
System.out.println("ERROR: row=" + row + ", i=" + i + ", text=" + text);
return null;
}
}
CAVEAT: This is for helping you troubleshoot ONLY. You definitely wouldn't want to release this in "production code" ;)
What is the NumberFormatException?
Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
Offtopic:
A thing that i can notice is that both filesnames have the same name. So you will verify the same file 2 times.
String filename1 = "magicSquaresData.txt", filename2 = "magicSquaresData.txt";
I checked your program and you error appears when you put like this on a file:
1. 5 5
2. 5 5
So the error shows beacause you are trying to parse to int the String "5 5". So your code pick the all line and tries to convert to int and " " it's not an int. And there lives the NumberFormatException error.
How do to solve it?
The function that we will work on is the one that you pass from file to an array in
private static int[][] getArray(String filename) throws FileNotFoundException{
The of the function is after we read the file.
As you said, you are leading with a 2d array so to insert all the numbers we need to have loops for each dimension on the array.
So we will start from there.
I will use a while beacause we are dealing with a string and it's easier to verify the text that its left on the line. Will add a new int variable that starts in 0 to pass in every column of a line to use with the while loop. And with this we got this:
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
whileIterator++;
}
whileIterator = 0;
}
Next setep, we will divide in 2 behaviors because we will substring the String that has in the line, and will work differently when it's the last number that we are verifying:
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
if(whileIterator + 1 == size){//If its the last iteration that we need in a line
}else{//All other iterations
whileIterator++;
}
whileIterator = 0;}
To finalize let's add the new logic to insert in nos array. So lets pick all line for example 2 7 6 and we want to add the number 2, so lets do that. You just need to substring(int startIndex, int finalIndex) the line and add to the nos array. After that let remove the number and the space ("2 ") from the line that we are veryfying.
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
if(whileIterator + 1 == size){//If its the last iteration that we need
nos[rows][whileIterator] = Integer.parseInt(line.substring(0));//Add to array
line = "";//To not pass the while verification
}else{//All other iterations
nos[rows][whileIterator] = Integer.parseInt(line.substring(0, line.indexOf(" ")));//Add to array
line = line.substring(line.indexOf(" ") + 1);//remove the number we added behind
}
whileIterator++;
}
whileIterator = 0;}
And here you go, that how you add the numbers to an array and don't get the error.
If you need some further explanation just ask. Hope it helps :)
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
}
}
I have this piece of code :
import java.util.*;
class HelloWorld {
public static void main(String args[]) {
Scanner ob = new Scanner(System.in);
int t = ob.nextInt(); //no. of Test Cases
ob.next(); // for next input whether exception occurs or not
int a = 0, c = 0;
for (int j = 0; j < t; j++)
{
a = 0; c = 0;
String str = ob.nextLine();
String [] spstr = str.split("\\s+");
try
{
for (int i=0 ; i<spstr.length ; i++)
{
if(spstr[i].equals("")) {i--;}
else {
c = c + Integer.parseInt(spstr[i]);
}
}
System.out.println(c);
} catch (Exception e) {
System.out.println("Invalid Input");
}
}
}
}
What this code do is add any no.s of integers in a single line. Before doing this, I have a Test Case int t. This decides how many inputs must be taken. But this results to an infinite loop even when I am entering integer value.
I have seen this post:
How to handle infinite loop caused by invalid input using Scanner which have many answers on how to get rid of this. I have followed the answers, but I have not yet solved this issue.
Note: When I use int t=5;, it works fine. But in this case too, if exception is caught twice, same thing happens.
Please tell me how to solve this infinite loop error ?
Thanks in Advance :)
Simply use ob.nextLine() to ignore it. I fixed the code for you and it works as it should. Your code had several issues which I have mentioned.
import java.util.*;
class HelloWorld {
public static void main(String args[]) {
Scanner ob = new Scanner(System.in);
int t = ob.nextInt();
ob.nextLine();
int a = 0, c = 0;
for (int j = 0; j < t; j++)
{
a = 0; c = 0;
String str = ob.nextLine();
if(str.trim().length()>0){
String [] spstr = str.trim().split("\\s+");
try
{
for (int i=0 ; i<spstr.length ; i++)
{
c = c + Integer.parseInt(spstr[i]);
}
System.out.println(c);
} catch (NumberFormatException e) {
System.out.println("Invalid Input");
}
}
}
}
}
if(spstr[i].equals("")) {i--;} is pointless and wrong logic in fact which will throw your program into an infinite loop. Simply trim the String and check if it is empty as I have done.
Do not simply catch Exception superclass. This is bad for debugging. The Exception raised here is NumberFormatException which you should catch.
To begin with, proper indentation helps make code easier to read.
class HelloWorld {
public static void main(String args[]) {
Scanner ob = new Scanner(System.in);
int t = ob.nextInt(); //no. of Test Cases
ob.next(); // for next input whether exception occurs or not
int a = 0, c = 0;
for (int j = 0; j < t; j++) {
a = 0;
c = 0;
String str = ob.nextLine();
String[] spstr = str.split("\\s+");
try {
for (int i = 0; i < spstr.length; i++) {
if (spstr[i].equals("")) {
i--;
} else {
c = c + Integer.parseInt(spstr[i]);
}
}
System.out.println(c);
} catch (Exception e) {
System.out.println("Invalid Input");
}
}
}
}
There's several problems.
int t = ob.nextInt(); //no. of Test Cases
ob.next(); // for next input whether exception occurs or not
I don't know what you're hoping to accomplish here. That is not what the linked answer has as a solution. The linked answer is referring to cases where the input is invalid and specifically references catching the exception like so:
try {
int x = ob.nextInt();
} catch (InputMismatchException e) {
ob.next();
}
Which I seriously doubt has anything to do with your problem unless you're intentionally entering bad data.
Then there's this, the most likely culprit considering it's a potential infinite loop at first blush.
for (int i = 0; i < spstr.length; i++) {
if (spstr[i].equals("")) {
i--;
} else {
c = c + Integer.parseInt(spstr[i]);
}
}
If i is 5 and spstr[i].equals("") returns true then i becomes 4, the else is skipped and i is incremented back to 5 ad infinitum.
I have a code where in, an array is to be defined, in which the size is based on user input. How do I do that?
My code is as follows:
public static void main(String args[]) throws Exception {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of layers in the network:");
int Nb_Layers = in.nextInt();
int[] Hidden_layer_len = new int[Nb_Layers];
for (int i = 0; i < Nb_Layers-1; i++)
{
System.out.println("Enter the length of layer" +(i+1)+":");
Hidden_layer_len[i] = in.nextInt();
if(i == 0)
{
double [][] E = new double[Hidden_layer_len[i]][1];//This is the array I need based on the size mentioned.
}
}
System.out.println(E);
}
I want this to be a 2D array. Any suggestions would be appreciated. thank you!
You can define the array outside the for loop and assign inside. E.g.
double[][] E = null;
for (int i = 0; i < Nb_Layers - 1; i++) {
System.out.println("Enter the length of layer" + (i + 1) + ":");
Hidden_layer_len[i] = in.nextInt();
if (i == 0) {
E = new double[Hidden_layer_len[i]][1];
}
}
This way it will be available when you print it at the end.
By the way you probably want to print it like this
System.out.println(Arrays.deepToString(E));
import java.io.*;
import java.util.Scanner;
public class Kazarian_ArrayProcessing
{
public static void main(String[] args) throws Exception
{
inputData();
mean(data);
// I am trying to pass in an array since the mean method
// accepts an array in the parameters but I'm having trouble doing that
// since the array doesn't have a fixed value but instead pulls from a
// specific file
/*sum(data);
max(data);
min(data);*/
}
// checks if file exists and if it does it pulls in the values from the file and
// puts them into an array called data
public static int[] inputData() throws Exception
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a file name: ");
String inputFile = keyboard.next();
File file = new File(inputFile);
if (!file.exists())
{
System.out.println("This file does not exist!");
System.exit(0);
}
// do this stuff if file does exist
Scanner readFrom = new Scanner(file);
int numberOfElements = readFrom.nextInt();
int [] data = new int[numberOfElements];
for (int i = 0; i < data.length; i++)
{
if (readFrom.hasNextInt())
{
int start = readFrom.nextInt();
data[i] = start;
//System.out.println(data[i]);
}
}
return data;
}
// calculates the mean by pulling in the values from a text file and adding them to
// total and then taking the average
public static double mean(int[] array) throws Exception
{
double average;
double total = 0;
File file = new File("inputFile1.dat");
Scanner readFrom = new Scanner(file);
readFrom.nextInt();
for (int i = 0; i < array.length; i++)
{
if (readFrom.hasNextInt())
{
int start = readFrom.nextInt();
array[i] = start;
}
}
for (int j = 0; j < array.length; j++)
{
total += array[j];
}
average = total / array.length;
System.out.printf("The mean of all elements is: %.2f" + "\n" , average);
return average;
}
I need to somehow pass in an array to the mean method for it to do its job but I'm having
trouble doing so since my array doesn't have a fixed number of elements inside of it and I don't know how to deal with it this way.
int[] data = inputData();
mean(data);
where do you get data from when you call mean?
you need to assign an array to data before you can send it as a parameter to mean(int[]array);
calling inputData returns an array so store its contents into data and then pass data to mean() using mean(data); //see code above
Just change your first line to int[] data = inputData();. You're not saving the array once you create and return it.