Input matrices from a file - java

I'm trying to read 2D matrices from an input file.The​ ​input​ ​file​ ​contains​ ​a​ ​series​ ​of​ ​inputs.​ ​First​ ​line​ ​contains​ ​the matrix ​size​ ​​n.​Next​ ​​n line​ ​contains​ ​​n ​integer​ ​each,​ ​i.e.,​ ​an​ ​n*n matrix.​​The​ ​file​ ​ends with​ ​a​ ​zero​ ​as​ ​matrix ​size.A small sample is below.
2
1 1
1 1
3
3 1 2
1 1 2
2 2 1
6
1 2 3 4 2 3
3 3 4 5 2 1
4 3 3 1 2 3
5 4 3 6 2 1
3 2 4 3 4 3
2 3 4 1 5 6
0
I wrote the following code but it doesn't show what i need.
import java.util.*;
import java.io.*;
public class trial{
public static void main(String[] args) {
try{
//System.out.println(new File("input.txt").getAbsolutePath());
Scanner input = new Scanner(new File("./input.txt"));
while (true){
int n = input.nextInt();
//System.out.println("%d",n);
if(n!=0) {
int[][] grid = new int[n][n];
while (input.hasNext()) {
for (int row = 0; row < n; row++) {
for (int column = 0; column < n; column++) {
grid[row][column] = input.nextInt();
System.out.printf(" %d ", grid[row][column]);
}
System.out.println();
}
System.out.println("Array done");
}
}
input.close();
}
}catch (FileNotFoundException e){
System.out.println("File not found");
}
}
}
The code output is below.It always generates a 2*2 matrix.
1 1
1 1
Array done
3 3
1 2
Array done
1 1
2 2
Array done
2 1
6 1
Array done
2 3
4 2
Array done
3 3
3 4
Array done
5 2
1 4
Array done
3 3
1 2
Array done
3 5
4 3
Array done
6 2
1 3
Array done
2 4
3 4
Array done
3 2
3 4
Array done
1 5
6 0
Array done

First of all, it looks like you want to stop if the user inputs a size of 0, but you don't actually do that, instead you just loop forever. Second, after reading the first matrix, you close the scanner, which isn't what you should do. input.close() should be outside the while loop. Try this.
try {
Scanner input = new Scanner(new File("./input.txt"));
int n;
while (input.hasNextInt() && (n = input.nextInt()) > 0) {
int[][] grid = new int[n][n];
for (int row = 0; row < n; row++) {
for (int column = 0;
column < n && input.hasNextInt(); column++) {
grid[row][column] = input.nextInt();
System.out.printf("a %d ", grid[row][column]);
}
System.out.println();
}
System.out.println("Array done");
}
input.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
}

In your code you are not check when the nextInt is a size and when is a number in matrix . Another thing is that a 0 in size it is for you an EOF , so you shoul get out .
Below a working example :
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
try{
Scanner input = new Scanner(new File("pathtofile"));
while (true){
int n = input.nextInt();
//System.out.println("%d",n);
int cont =0;
if(n!=0) {
int[][] grid = new int[n][n];
while (input.hasNext() && cont != n) {
for (int row = 0; row < n; row++) {
for (int column = 0; column < n; column++) {
grid[row][column] = input.nextInt();
System.out.printf("a %d ", grid[row][column]);
}
System.out.println();
cont++;
}
System.out.println("Array done");
}
}
else{
input.close();
break;
}
}
}catch (FileNotFoundException e){
System.out.println("File not found");
}
}}
Result :

Related

Java - Vertical Histogram troubleshoot: broken max value?

So after much trial and error I converted my horizontal histogram to a vertical one, at least partially.
It seems that instead of reading the highest number of times used, it simply reads the value of the highest-used number:
How many input values [max:30]?
5
Enter 5 numbers.
2
1
2
0
2
Number Occurrence
0 1
1 1
2 3
========= Vertical Bar ========
2 | *
1 | * * *
===============================
| No | 0 1 2 3 4 5 6 7 8 9
===============================
leaves out the max height of 3 and removes an asterisk
How many input values [max:30]?
1
Enter 1 numbers.
5
Number Occurrence
5 1
========= Vertical Bar ========
5 |
===============================
| No | 0 1 2 3 4 5 6 7 8 9
===============================
does not print
5
Enter 5 numbers.
3
3
3
3
3
Number Occurrence
3 5
========= Vertical Bar ========
3 | *
===============================
| No | 0 1 2 3 4 5 6 7 8 9
===============================
prints the wrong max, the wrong number of asterisks, and in the wrong spot
How many input values [max:30]?
10
Enter 10 numbers.
5
4
3
2
1
1
2
3
4
5
Number Occurrence
1 2
2 2
3 2
4 2
5 2
========= Vertical Bar ========
5 |
4 |
3 |
2 | * * * * *
1 | * * * * *
===============================
| No | 0 1 2 3 4 5 6 7 8 9
===============================
adds whitespace for 5-3
10
Enter 10 numbers.
2
2
3
3
3
4
4
4
4
1
Number Occurrence
1 1
2 2
3 3
4 4
========= Vertical Bar ========
4 | *
3 | * *
2 | * * *
1 | * * * *
===============================
| No | 0 1 2 3 4 5 6 7 8 9
===============================
works as intended although not by design
public class Histogram
{
public static void main(String[] args) {
//variables
Scanner keyboard = new Scanner(System.in);
int numInputs = 1, temp, maximum = 0;
int[] numbers = new int[31];
int[] count = new int[31];
boolean success = false;
//start of program
System.out.println("How many input values [max:30]?");
//while no valid input
while (!success) {
try {
numInputs = keyboard.nextInt(); //get a number
numInputChecker(numInputs); //is it valid?
success = true; //ok
} catch (Exception e) //else get a new number
{
keyboard.nextLine();
System.out.println("Whole numbers 1 through 30 only, please.");
}
}
//reset the loop checker
success = false;
//read numbers to fill that array
System.out.println("Enter " + numInputs + " numbers.");
for (int i = 0; i < numInputs; i++) //from 0 to max number
{
while (!success) //while no valid number
{
try {
numbers[i] = keyboard.nextInt(); //fill the current cell with a number
numberChecker(numbers[i]); //is it valid?
success = true; //ok
} catch (Exception e) //else get a new number
{
keyboard.nextLine();
System.out.println("Whole numbers 0 through 9 only, please.");
}
}
success = false;
}
//for cells not used
for (int i = numInputs; i < numbers.length; i++) {
numbers[i] = 10; //fill with garbage data (to prevent false positive 0s)
}
//take the input and count each use of element
for (int i : numbers) //for 0 to max number
{
temp = i; //get the current value of the cell
count[temp]++; //add the use of that value to a new array's cell
}
System.out.println("Number Occurrence");
for (int i = 0; i < count.length; i++) //from 0 to 9 (expected)
{
if ((count[i] > 0) && (count[i] <= 9)) //if cell not empty and has valid data
{
System.out.println(i + " " + count[i]); //print the current cell and how many times it was used
}
}
System.out.println(); //spacer
//histogram segment
//find the highest-used number
for (int i : count) //for each number
{
if(i > maximum) //if greater than the current max
{
maximum = i; //set to max
}
}
System.out.println("========= Vertical Bar ========");
for (int i = maximum; i > 0; i--) //max through 1
{
if ((count[i] > 0) && (count[i] <=9)) //if has valid data
{
System.out.print((i) + "\t | "); // print the number and a nice line for readability
for (int j = 0; j < count.length; j++) //for the number of times that number was used
{
if ((count[j] > 0) && (count[j] <=9)) //if has valid data
{
if (count[j] >= i) //if that number the max
{
System.out.print("* "); //print an asterisk
}
else
{
System.out.print(" "); //"skip" and keep alignment
}
}
}
System.out.println(); //make a new line
}
}
System.out.println("==============================="); //footer
System.out.println("| No | 0 1 2 3 4 5 6 7 8 9");
System.out.println("===============================");
}
static void numInputChecker(int integer) throws Exception
{
if ((integer < 1) || (integer > 30)) //if 0 or negative, or if 31+
{
throw new Exception(); //say no
}
}
static void numberChecker(int integer) throws Exception
{
if ((integer < 0) || (integer > 9)) //if negative or 10+
{
throw new Exception(); //say no
}
}
}
Your problem is that you have too many if blocks in your asterisks output logic. You're deciding not to print anything at some horizontal positions based on the data, when what you really want to do is print two characters (either a space plus an asterisk or two spaces) at each position horizontally, regardless of if you saw any numbers at that position. So your print code gets simpler and does the right thing if you take out all but one if block to arrive at this:
System.out.println("========= Vertical Bar ========");
// for each count, starting from the max...
for (int i = maximum; i > 0; i--)
{
System.out.print((i) + "\t | ");
// for each number from 0 to the largest number we saw
for (int j = 0; j < count.length; j++)
{
// If the count at this position horizontally is greater than or
// equal to the count vertically (the line number we're on), then
// print an asterisk, else print a blank space.
if (count[j] >= i).
{
System.out.print("* ");
}
else
{
System.out.print(" ");
}
}
System.out.println();
}
System.out.println("===============================");
System.out.println("| No | 0 1 2 3 4 5 6 7 8 9");
System.out.println("===============================");
Here's a pretty complicated result that I was using for testing:
Input:
int[] numbers = { 1, 2, 3, 4, 5, 1, 1, 3, 3, 5, 5, 3, 3, 5, 5, 7 };
Result:
Number Occurrence
1 3
2 1
3 5
4 1
5 5
7 1
========= Vertical Bar ========
5 | * *
4 | * *
3 | * * *
2 | * * *
1 | * * * * * *
===============================
| No | 0 1 2 3 4 5 6 7 8 9
===============================
public class Histogram
{
public static void main(String[] args)
{
//variables
Scanner keyboard = new Scanner(System.in);
int numInputs = 1, temp, maximum = 0;
int[] numbers = new int[31];
int[] count = new int[31];
boolean success = false;
//start of program
System.out.println("How many input values [max:30]?");
//while no valid input
while (!success)
{
try
{
numInputs = keyboard.nextInt(); //get a number
numInputChecker(numInputs); //is it valid?
success = true; //ok
} catch (Exception e) //else get a new number
{
keyboard.nextLine();
System.out.println("Whole numbers 1 through 30 only, please.");
}
}
//reset the loop checker
success = false;
//read numbers to fill that array
System.out.println("Enter " + numInputs + " numbers.");
for (int i = 0; i < numInputs; i++) //from 0 to max number
{
while (!success) //while no valid number
{
try
{
numbers[i] = keyboard.nextInt(); //fill the current cell with a number
numberChecker(numbers[i]); //is it valid?
success = true; //ok
} catch (Exception e) //else get a new number
{
keyboard.nextLine();
System.out.println("Whole numbers 0 through 9 only, please.");
}
}
success = false;
}
//for cells not used
for (int i = numInputs; i < numbers.length; i++)
{
numbers[i] = -1; //fill with garbage data (to prevent false positive 0s)
}
//take the input and count each use of element
for (int i : numbers) //for 0 to max number
{
if (i != -1) //if valid data
{
temp = i; //get the current value of the cell
count[temp]++; //add the use of that value to a new array's cell
}
}
System.out.println("Number Occurrence");
for (int i = 0; i < count.length; i++) //from 0 to 9 (expected)
{
if (count[i] > 0) //if cell has valid data
{
System.out.println(i + " " + count[i]); //print the current cell and how many times it was used
}
}
System.out.println(); //spacer
//histogram segment
//find the highest-used number
for (int k : count) //for 0 to 9
{
if (k > maximum) //if greater than the current max
{
maximum = k; //set to max
}
}
System.out.println("========= Vertical Bar ========");
for (int i = maximum; i > 0; i--) // from max to 1
{
System.out.print((i) + "\t | "); //print the number and a spacer for visibility
for (int j = 0; j < count.length; j++) // from 0 to max
{
if (count[j] >= i) // If the count at this position horizontally is greater than or
// equal to the count vertically (the line number we're on)
{
System.out.print("* "); //print an asterisk
}
else
{
System.out.print(" "); //else print a blank
}
}
System.out.println(); //spacer
}
//footer
System.out.println("===============================");
System.out.println("| No | 0 1 2 3 4 5 6 7 8 9");
System.out.println("===============================");
}
static void numInputChecker(int integer) throws Exception
{
if ((integer < 1) || (integer > 30)) //if 0 or negative, or if 31+
{
throw new Exception(); //say no
}
}
static void numberChecker(int integer) throws Exception
{
if ((integer < 0) || (integer > 9)) //if negative or 10+
{
throw new Exception(); //say no
}
}
}

Last line of textfile not storing correctly into 2D array

My scanner is not accessing last line of my text file correctly, thus is storing the last line of the text file as all 0's into my 2D array instead of what is actually there. I believe I have provided everything that would give context as to what is going wrong, but if more info is needed I can update this question, thanks in advance.
//Creates 2-d array object, stores values from file.
public DominoSort (String fileName) throws java.io.FileNotFoundException{
this.grid = new int [7][8]; //2-d array to hold values from text file
Scanner br = new Scanner(new File(fileName));
String line = br.nextLine();
int r = 0;
int c = 0;
while (br.hasNextLine) {
String[] row = line.split("\\s+");
for (String s : row) {
this.grid[r][c] = Integer.parseInt(s);
c++;
}
line = br.nextLine();
r++;
c = 0;
}
//this.setS = new ArrayList<>();
//this.pairMappings = new ArrayList<ArrayList<dominoLocation>>();
br.close();
}
//Print grid function, prints out the grid
public void printGrid() {
for(int r = 0; r < this.grid.length; r++) {
System.out.println("");
for(int c = 0; c < this.grid[r].length; c++) {
System.out.print(this.grid[r][c] + " ");
}
}
System.out.println("");
}
//Driver for checking
public static void main(String[] args) throws IOException {
// String line;
//System.out.println(new File(".").getAbsolutePath());
Scanner input = new Scanner(System.in); //get textfile name from user input
System.out.print("Enter the file name: ");
String fileName = input.next();
DominoSort dom = new DominoSort(fileName); //this call populates the 2-d array object
//dom.solvePuzzle(6);
dom.printGrid(); //prints 2d array for output
//dom.solvePuzzle(6);
}
text file used for testing / expected output:
3 3 4 2 2 0 0 0
4 6 3 6 3 1 4 1
5 5 4 1 2 1 6 5
5 6 0 2 1 1 5 3
5 4 4 2 6 0 2 6
3 0 4 6 6 1 3 1
2 0 3 2 5 0 5 4 {Notice this line}
actual output:
3 3 4 2 2 0 0 0
4 6 3 6 3 1 4 1
5 5 4 1 2 1 6 5
5 6 0 2 1 1 5 3
5 4 4 2 6 0 2 6
3 0 4 6 6 1 3 1
0 0 0 0 0 0 0 0 {this line is not right}
Your problem lies within the nested while/for loop. It reaches the end condition before all the lines are read. (The nextLine() method doesn't have any more lines before you read the last line). You can see this by putting an extra 1 or 2 lines in your file at the very end, making it show the last lines.
There are a few ways to fix it, one of them is by just adding on an extra for loop after the while loop to compute the last line individually:
while (br.hasNextLine()) {
String[] row = line.split("\\s+");
for (String s : row) {
this.grid[r][c] = Integer.parseInt(s);
c++;
}
line = br.nextLine();
r++;
c = 0;
}
String[] row = line.split("\\s+");
for (String s : row) {
this.grid[r][c] = Integer.parseInt(s);
c++;
}
or alternatively, don't increment the line on the first run:
while (br.hasNextLine()) {
String[] row = line.split("\\s+");
for (String s : row) {
this.grid[r][c] = Integer.parseInt(s);
c++;
}
if (r != 0)
line = br.nextLine();
r++;
c = 0;
}

print 2 arrays like matrix for my assignment

I want my output to be like this e.g. if the user inputs 3:
without using 2d array
1 2 3
1 1 2 3
2 1 4 6
3 3 6 9
My code so far
public void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
int[] cloumnarray = new int[i];
int[] rowarray = new int[i];
for (int z = 0; z <= i - 1; z++) {
cloumnarray[z] = z + 1;
rowarray[z] = z + 1;
}
for (int j = 0; j < i; j++) {
System.out.println(cloumnarray[j] * rowarray[j]);
}
}
I tried different options and can't get this to work properly.
public static void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
for (int a = 0; a <= i; a++) {
for (int b = 0; b <= i; b++) {
// top corner, don't print nothing
if (a == 0 && b == 0) System.out.print("\t");
// top row 0-1, 0-2, 0-3 etc... just 1,2,3...
else if (a == 0) {
System.out.print(b + "\t");
// last line, print extra line break
if (b == i)
System.out.print("\n");
}
// first column 1-0, 2-0, 3-0... just a + space (tabulator)
else if (b == 0) System.out.print(a + "\t");
// any other cases, are candidates to multiply and give result
else System.out.print(a*b + "\t");
}
//look this is out of scope of nested loops, so,
// in each a iteration, print line break :)
System.out.print("\n");
}
}
public static void main(String[] args) throws Exception {
matrixmutilplication();
}
OUTPUT (3)
1 2 3
1 1 2 3
2 2 4 6
3 3 6 9
OUTPUT (5)
1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25
But problem (for me) is the numbers are not padded in the natural order, so, to achieve your goal, exactly as in your demo, will need a bit of padding like this
public static void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
for (int a = 0; a <= i; a++) {
for (int b = 0; b <= i; b++) {
if (a == 0 && b == 0) System.out.print("\t");
else if (a == 0) {
System.out.print(String.format("%3s", b));
if (b == i)
System.out.print("\n");
}
else if (b == 0) System.out.print(a + "\t");
else System.out.print(String.format("%3s", a*b));
}
System.out.print("\n");
}
}
public static void main(String[] args) throws Exception {
matrixmutilplication();
}
OUTPUT (7)
1 2 3 4 5 6 7
1 1 2 3 4 5 6 7
2 2 4 6 8 10 12 14
3 3 6 9 12 15 18 21
4 4 8 12 16 20 24 28
5 5 10 15 20 25 30 35
6 6 12 18 24 30 36 42
7 7 14 21 28 35 42 49
What looks quite good :)
So this should be pretty simple.
public void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
for (int a = 0; a < i; a++) {
for (int b = 0; b < i; b++) {
System.out.print(a*b + "\t");
}
System.out.print("\n");
}
}
Whenever you're working with a matrix involving two arrays (especially if you're trying to a solve a problem that deals with patterns), you want to have a nested for loop like so:
for(int row = 0; row < numSelected; row++) {
for(int col = 0; col < numSelected; col++) {
...
}
}
That way, each cell in the matrix will be covered. Now using that, you can try multiplying the row index and the col index and storing that to the correct cell.

Removing duplicates from sorted Char array

I am trying to take the string below, convert it to an array, sort the array, then take out any duplicates. I have gotten to the sorted part, but when I run this in hopes for the duplicates being removed, it seems to print position instead of the value there.
This is also counting spaces as length, giving me a length of 59 for this.
Can I get some help figuring out what I need to change?
Thank you all!
import java.util.*;
public class Challenge208 {
public static void main(String[] args) {
String numbers = "3 1 3 4 4 1 4 5 2 1 4 4 4 4 1 4 3 2 5 5 2 2 2 4 2 4 4 4 4 1";
char[] chars = numbers.toCharArray();
Arrays.sort(chars);
System.out.println(chars);
int current = chars[0];
boolean found = false;
for (int i = 0; i < chars.length; i++) {
if (current == chars[i] && !found) {
found = true;
}else if (current != chars[i]) {
System.out.print(" " + current);
current = chars[i];
found = false;
}
}
System.out.print(" " + current);
}
}
current should be type char not int. To get rid of the spaces, you could print if current is not a space.
Instead of using array u can use treeset.. It will have a sorted order and no duplicates.. But if in your scenario you need array in that case first your current variable is int instead of char and you are not removing any of the duplicates.you are just printing that whenever you find that char even if that item does not have any duplicates and that only for char[0]
You are not getting the index of the number but its ascii value. For more details: http://www.asciitable.com/
But solution is as follows:
import java.util.*;
public class Challenge208 {
public static void main(String[] args) {
String numbers = "3 1 3 4 4 1 4 5 2 1 4 4 4 4 1 4 3 2 5 5 2 2 2 4 2 4 4 4 4 1";
char[] chars = numbers.toCharArray();
char[] results = new char[10];
Arrays.sort(chars);
System.out.println(chars);
char current = chars[0];
int size = 0;
boolean found = false;
for (int i = 0; i < chars.length; i++) {
if (current == chars[i] && !found) {
found = true;
}else if (current != chars[i]) {
System.out.print(" " + current);
size++;
current = chars[i];
found = false;
}
}
System.out.print(" " + current);
System.out.print("\n"+size);
}
}

Reading ints into a multidimensional array

My problem occurs during the for loops to read in the values from the file into my scores array. The program reads in and prints the first 6 values or 2 lines of ints, but then I get ArrayIndexOutOfBoundsException: 2
I have no idea why this is stopping there. If I have j<1000, it will read 17 values. Anyway, the file I'm reading in is below (wasn't sure the formatting for a text file).
Any help would be appreciated
Andy Matt Tom
3 2 3
4 4 5
3 3 2
2 2 2
2 4 2
2 3 2
4 4 5
2 3 3
4 3 5
3 3 6
2 2 5
3 3 3
3 3 2
3 2 4
3 2 6
3 4 3
2 3 2
2 2 2
50 52 62
public static void main( String args[] )
{
try
{
if (args.length<1)
{
System.out.printf("\n...You must enter the name of a file\n");
System.exit(0);
}
Scanner infile = new Scanner ( new File(args[0]) );
int par= 3;
int play= 18;
String[] players= new String[play];
int k=0;
int scores[][]= new int[play-1][par-1];
while(infile.hasNext())
{
players[k]=infile.next();
k++;
if (k==play)
break;
}
for(int j=0; j<par; j++)
{
for (int i=0; i<play; i++)
{
scores[j][i]=infile.nextInt();
System.out.println(scores[j][i]);
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Bug");
System.exit(0);
}
}
int scores[][] = new int [play-1][par-1];
Why -1? That's where your AIOOB is coming from.
There are two issues:
int scores[][] = new int[play-1][par-1]; // Why -1 ?
and:
for(int j=0; j<par; j++) // should be 'j < play' as 'j'
// is index to dimension
// with size 'play'
{
for (int i=0; i<play; i++) // should be 'i < par' as 'i' is
// index to dimension with
// size 'par'
{
scores[j][i]=infile.nextInt();
System.out.println(scores[j][i]);
}
}
Actually, there are three issues.
There are only 3 players, not 18
You need a 18x3 array, not a 17x2 array
[i][j] instead of [j][i]
Diff of your code against my modified version (which works like a charm):
22c22
< String[] players= new String[play];
---
> String[] players= new String[par];
24c24
< int scores[][]= new int[play-1][par-1];
---
> int scores[][]= new int[play][par];
32c32
< if (k==play)
---
> if (k==par)
41,42c41,42
< scores[j][i]=infile.nextInt();
< System.out.println(scores[j][i]);
---
> scores[i][j]=infile.nextInt();
> System.out.println(scores[i][j]);

Categories

Resources