User enters a text file at command-line and my prog. will take the text, create an array with the number of rows (vertices) of the first number showed, then fill the 2d array with the remaining numbers. Finally it will display if # connects to # display T, else display F. I haven't completed it, and am stuck on it just filling the array and displaying the numbers in the array.
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class AdjMatrix {
public static void main(String[] args) {
//ArrayList<Integer> list = new ArrayList<Integer>(); //Arraylist to store all integers in the array
//int n = 0; //Vertices
final int COLS = 2; //Number of columns
int[][] array = null;
int lineNumber = 0;
String line = "";
if(args.length > 0)
{
try
{
java.io.File file = new java.io.File(args[0]);
Scanner in = new Scanner(file);
//Reading the file
while(in.hasNext())
{
line = in.next();
lineNumber++;
if(lineNumber == 1)
{
//n = Integer.parseInt(line);
array = new int[Integer.parseInt(line)][COLS];
System.out.println(Integer.parseInt(line));
}
else
{
String[] tokens = line.split(",");
for(int x = 0; x < tokens.length; ++x)
for(int j = 0; j < tokens.length; ++j)
{
array[x][j] = Integer.parseInt(tokens[x]);
}
}
}
in.close();
}//End try
catch(FileNotFoundException e)
{
System.err.println("File was either not found or it does not exist.");
System.out.printf("\n");
}//End catch
}//End Commandline param entry
for(int i = 0; i < array.length; i++)
for(int j = 0; j < array.length; j++)
System.out.println(" " + array[i][j]);
}
}
I put in System.out.println(Integer.parseInt(line)); to see if it grabs the number and puts it in the rows # for the array, that's successful. Any help is appreciated. Been on it for a good while and any assistance is appreciated.
EDIT
Sorry, forgot to add the input file.
integer.txt
9
1,2
2,6
6,2
5,1
6,5
3,2
6,3
3,7
8,7
9,9
9 being the number that establishes the # of rows. Then the program grabs all numbers after 9
It looks like you're initializing a firstLine by 2 dimension array,
array = new int[Integer.parseInt(line)][COLS];
but you're trying to fill it with line.length by line.length elements.
for(int x = 0; x < tokens.length; ++x)
for(int j = 0; j < tokens.length; ++j)
{
array[x][j] = Integer.parseInt(tokens[x]);
}
This seems like a bug, but without seeing a sample file, I can't say for sure.
Related
I'm trying to read a file with a line of numbers and put it into a 2d array
Here is the prompt:
Create a file of integers. Write a program that first tests whether the number of integers is a square of some integer n. If so, create a 2D array of size n×n. Then, read the numbers into the array. Finally, display the array and test whether the array forms a magic square, that is, whether the sums of rows, columns, and diagonals are all equal. For example, if the file includes numbers
6 7 2 1 5 9 8 3 4
so that n = 3, then the array
6 7 2
1 5 9
8 3 4
is displayed along with the message that the array is a magic square.
I have up to reading the file and putting it into an array but am stuck and I don't know how to put the numbers into the array I have made.
Here is my Code so far:
import java.io.*;
import java.lang.*;
//import java.util.Arrays;
class Program8 {
Scanner kb = new Scanner(System.in);
void print2Darray(int[][] a){
for(int row = 0; row < a.length; row++) {
for(int col = 0; col < a[row].length ; col++)
System.out.print(a[row][col] + " ");
System.out.println();
}
}
void magicSquare(){
Scanner fIn;
System.out.print("Enter the name of a file: ");
String s = kb.nextLine();
try {
fIn = new Scanner(new FileInputStream(s));
double x = 0;
// double y = 0;
// double z = 0;
int cnt = 0;
while(fIn.hasNextDouble()){
x = fIn.nextDouble();
cnt++;
System.out.println(cnt);
}
int sqrt = (int)Math.sqrt(cnt);
System.out.println(sqrt);
int [][] magicSqaure = new int [sqrt][sqrt];
print2Darray(magicSqaure);
//BufferedReader br = new BufferedReader(new FileInputStream(s));
while(fIn.hasNextDouble()){
for (int i = 0; i < magicSqaure.length; i++){
//input from file
for(int j = 0; i < magicSqaure.length; j++)
//input from file
}
//for(int j = 0; j < i; j++)
// z = fIn.nextDouble();
//System.out.println(Arrays.toString(magicSqaure));
// print2Darray(magicSqaure);
}
}catch(IOException e){
}
}
public static void main(String[] args) {
Program8 lab = new Program8();
lab.magicSquare();
}
}
I have a question about stop array input limit then the result to show the output.
Below is my coding have already set new float[3][3]:
import java.util.Scanner;
public class Clone2Darray {
public static float[][] clone(float[][] a) throws Exception {
float b[][] = new float[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
System.out.println ("Type nine float numbers two-dimensional array of similar type and size with line breaks, end by -1:");
float[][] a = new float[3][3];
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
String line = sc.nextLine();
if ("-1".equals(line)){
break;
}
a[i][j]=Float.parseFloat(line);
}
}
System.out.println("\n The result is:");
try {
float b[][] = clone(a);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}
The limit output is show me like below:
run:
Type float numbers in the two-dimensional array of similar type and size
with line breaks, end by -1:
5.33
9.33
63.33
6.36
3.55
7.25
2.33
3.66
The result is:
6.33 5.33 9.33
63.33 6.36 3.55
7.25 2.33 3.66
BUILD SUCCESSFUL (total time: 31 seconds)
My problem is want to stop limit float[3][3] and can unlimited key in the input until type -1 to stop the input. May I know how to remove the limit float[3][3] in the array? Hope anyone can guide me to solve my problem. Thanks.
At the point when you allocate memory for the two-dimensional array you have to tell the sizes of its elements, because memory will be allocated for that array and the amount of memory to be allocated must be known.
You can bypass this, by using some more dynamic types, like List and its popuplar implementation, ArrayList, even in a nested form. That's a nice thing to do, but then you will not have a "real" array.
The below code allows you to create the dynamic arrays.
import java.util.Scanner;
public class Clone2DArray {
public static float[][] clone(float[][] a) throws Exception {
float b[][] = new float[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
System.out.println("enter row size");
int row = Integer.parseInt(sc.nextLine());
System.out.println("enter column size");
int column = Integer.parseInt( sc.nextLine());
System.out.println ("Type float numbers two-dimensional array of similar type and size with line breaks:");
float[][] a = new float[row][column];
for (int i=0; i<row; i++){
for (int j=0; j<column; j++){
String line = sc.nextLine();
if ("-1".equals(line)){
break;
}
a[i][j]=Float.parseFloat(line);
}
}
System.out.println("\n The result is:");
try {
float b[][] = clone(a);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}
I need to read a file with a magic square in the format of:
#
# # #
# # #
# # #
where the first line represents the square size and create a 2d array with the file values.
I set up my readMatrix method to read through the lines, created a 2d array of the correct size and input each value to its correct position.
private int[][] readMatrix(String fileName) throws
FileNotFoundException {
int n;
File file = new File(fileName);
Scanner fileScan = new Scanner(file);
String line = fileScan.nextLine();
Scanner lineScan = new Scanner(line);
n = lineScan.nextInt();
square = new int[n][n];
while (fileScan.hasNextLine()) {
line = fileScan.nextLine();
while (lineScan.hasNext()) {
for (int i = 0; i < n; i++) {
lineScan = new Scanner(line);
for (int j = 0; j < n; j++) {
square[i][j] = lineScan.nextInt();
}
}
}
}
fileScan.close();
lineScan.close();
return square;
public int[][] getMatrix() {
int[][] copy;
int n = square.length;
copy = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
copy[i][j] = square[i][j];
}
}
return copy;
However the tester for this program displays a magic square of the correct dimensions but with all the values being 0 and fails the getMatrix method(I'm assuming because the returned square doesn't match the file square). I tried moving the scanner objects around(inside/outside) the for/while loops in the readMatrix and tried using parseInt/scan next instead of nextInt with no success. I am stumped.
Try this code is able to display 1 - 9 from the 3 x 3 matrix. The variable type can be changed to your need. I used 'char' for ease.
private static char[][] finalmatrix;
public static void main(String[] args) throws Exception {
finalmatrix = readMatrix("File.txt");
// Output matrix.
for (int i = 0; i < finalmatrix.length ;i++) {
for (int j = 0; j < finalmatrix[i].length ;j++) {
System.out.print(finalmatrix[i][j] + " ");
}
System.out.println("");
}
}
private static char[][] readMatrix(String fileName) throws IOException {
File file = new File(fileName);
Scanner scan = new Scanner(file);
int countRow = 0;
int countColumn = 0;
List temp = new ArrayList();
while (scan.hasNextLine()) {
String line = scan.nextLine();
for (int i = 0; i < line.length(); i++) {
// Count the number of columns for the first line ONLY.
if (countRow < 1 && line.charAt(i) != ' ') {
countColumn++;
}
// Add to temporary list.
if (line.charAt(i) != ' ') {
temp.add(line.charAt(i));
}
}
// Count rows.
countRow++;
}
char[][] matrix = new char[countRow][countColumn];
// Add the items in temporary list to matrix.
int count = 0;
for (int i = 0; i < matrix.length ;i++) {
for (int j = 0; j < matrix[i].length ;j++) {
matrix[i][j] = (char) temp.get(count);
count++;
}
}
scan.close();
return matrix;
}
Hi i want to fill a 2d array with comma separated values like this
3
1,2,3
4,5,6
7,8,0
first number the size of the array, the next values are the values of the array this is my code at the moment
//readfile
public static void leeArchivo()
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try
{
//read first value which is teh size of the array
size = Integer.parseInt(br.readLine());
System.out.println("size grid" + size);
int[][] tablero = new int[size][size];
//fill the array with the values
for (int i = 0; i < tablero.length; i++)
{
for (int j = 0; j < tablero[i].length; j++ )
{
tablero[i][j] = Integer.parseInt(br.readLine());
}
}
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
This method is working fine for me, just another question, this will work if I want to insert another 2d array of the same size next to the other?
public static void leeArchivo()
{
Scanner s = new Scanner(System.in);
size = Integer.parseInt(s.nextLine());
tablero = new int[size][size];
boolean exit = false;
while (!exit) {
for (int i = 0; i < size; i++) {
//quit commas to fill array
String valuesStrArr[] = s.nextLine().split(",");
for (int j = 0; j < size; j++) {
tablero[i][j] = Integer.parseInt(valuesStrArr[j]);
}
if (i == size - 1)
exit = true;
}
}
}
Example:
3
1,2,3
4,5,6
7,8,0
1,2,3
8,0,4
7,6,5
Solution using Scanner
Scanner s = new Scanner(System.in);
int size = Integer.parseInt(s.nextLine());
int[][] tablero = new int[size][size];
boolean exit = false;
while (!exit) {
for (int i = 0; i < size; i++) {
String valuesStrArr[] = s.nextLine().split(",");
for (int j = 0; j < size; j++) {
tablero[i][j] = Integer.parseInt(valuesStrArr[j]);
}
if (i == size - 1)
exit = true;
}
}
Scanner in = new Scanner(System.in);
int num = in.nextInt();
Use Scanner. Replace System.in with File.
First, you have to separate the elements.
You can do this using the String method split (https://www.javatpoint.com/java-string-split)
//fill the array with the values
for (int i = 0; i < tablero.length; i++)
{
String[] elements = br.readLine().split(",");
for (int j = 0; j < tablero[i].length; j++ )
{
tablero[i][j] = Integer.parseInt(elements[j]);
}
}
br.close();
Or you can use Scanner method, nextInt.
Regarding perfomance, the first option is better.
how to write two dimensional matrix as input and identifies the number with maximum number of occurrences in the matrix.
Example Input :
2 // no of rows
3 // no of columns
1 2 3 2 3 3 // here the matrix taken as input is 2 x 3 matrix. Remaining six numbers are values for the particular matrix. (elements in the first row are 1 2 3 and elements in the second row are 2 3 3)
Example output : 3
import java.util.*;
class ArrayOccurence
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
sc.nextLine();
int column = sc.nextInt();
sc.nextLine();
int element = 0;
int occurence = 0;
int arr[][] = new int[row][column]; // size of the array
for(int i=0; i < row; i++)
{
for(int j=0; j < column ; j++)
arr[i][j] = sc.nextInt();
}
//Do not modify the code above
/* Enter your code here */
// Do not modify code below
System.out.println("Matrix element "+element+" occurs "+occurence+" times in the matrix");
}
}
Substitute your line which says Enter your code here with the following:
ArrayList<Integer> a = new ArrayList<Integer>();
int oc = 0;
int number = 0;
for(int i=0; i < row; i++)
{
for(int j=0; j < column ; j++){
if(a.isEmpty()){
a.add(arr[i][j]);
}
else if(a.contains(arr[i][j])){
int temp=0;
for(int k=0; k<a.size(); k++){
if(a.get(k) == arr[i][j]){
temp++;
}
}
if(temp > oc){
number = arr[i][j];
oc = temp;
}
a.add(arr[i][j]);
}
else{
a.add(arr[i][j]);
}
}
}
Hope this helps.
You could use the double for loop again to count the occurence of each numbers:
for(int i=0; i < row; i++)
{
for(int j=0; j < column ; j++)
//count occurences with a HashMap<Integer,Integer> or something like that
}
Loop into your HashMap to find the one with most occurence..