Trouble reading a file and putting it into a 2d array - java

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();
}
}

Related

Multidimensional arrays from standard input

I'm trying to figure out how to read in a multidimensional array from standard input given the user provides the row and col size followed by integers of the array
e.g. Input:
2 3 <= row, col of array
8 3 10 < array integers
7 9 6
My code is currently:
int colA = scan.nextInt();
int rowA = scan.nextInt();
int[][] array = new int[rowA][colA];
for (int i = 0; i <rowA;i++){
for (int j=0; j<colA;j++){
array1[i][j] += scan.nextInt();
}
}
And the output of my array is: [[8,3,10,7,9,6]] but what I'd like to do is output [[8,3,10],[7,9,6]]
Here first the row and col value got from users is reversed that is the only mistake i could see
import java.util.Arrays;
import java.util.Scanner;
public class TwoDimensionalArray {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int rowA = scan.nextInt();
int colA = scan.nextInt();
int[][] array = new int[rowA][colA];
for (int i = 0; i < rowA; i++) {
for (int j = 0; j < colA; j++) {
array[i][j] += scan.nextInt();
}
}
for (int[] innerArray : array) {
System.out.println(Arrays.toString(innerArray));
}
}
}
This is a working one
There are some errors in your code.
You inverted the order of the dimensions asked to the users.
Use this:
int rowA = scan.nextInt();
int colA = scan.nextInt();
Instead of this:
int colA = scan.nextInt();
int rowA = scan.nextInt();
You wrote array1 instead of array in array1[i][j] += scan.nextInt();
Note that you can use array[i][j] = scan.nextInt(); instead of array[i][j] += scan.nextInt()

How to get the sum of each row in java using multidimensional array?

So i'm new at java and I'm currently trying to learn how to use array. So what i'm trying to do is to create a program the will as the user the numbers of rows and column and print the sum of the 2d array.
So the output should be like this:
Enter the number of row:2
Enter the number column:2
Enter a number:1
Enter a number:2
Enter a number:3
Enter a number:4
Output:
1 2 3
3 4 7
Here is my output:
Enter the number of row:2
Enter the number column:2
Enter a number:1
Enter a number:2
Enter a number:3
Enter a number:4
Output:
1 2
3 4
Somehow i cant find a way to sum each row.
Here is my code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int sum = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of row: ");
int row = input.nextInt();
System.out.print("Enter the number of column: ");
int column = input.nextInt();
int [][] array = new int[row][column];
for(int i = 0; i<row; i++){
for(int j = 0; j<column; j++){
System.out.print("Enter a number: ");
array[i][j] = input.nextInt();
}
}
for(int i = 0; i<row; i++){
for(int j = 0; j<column; j++){
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
}
I've been trying to do this for the past 3 hours and i cant seem to find a way to sum each row . I'm pretty new at this so any help would be greatly appreciated!
So basically, have a variable initialized for each row to calculate sumof all elements of the given row. Display it after the elements are displayed
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of row: ");
int row = input.nextInt();
System.out.print("Enter the number of column: ");
int column = input.nextInt();
int [][] array = new int[row][column];
for(int i = 0; i<row; i++){
for(int j = 0; j<column; j++){
System.out.print("Enter a number: ");
array[i][j] = input.nextInt();
}
}
for(int i = 0; i<row; i++){
int s = 0; // this variable calculates the sum
for(int j = 0; j<column; j++){
s+=a[i][j]; // summing elements of that row
System.out.print(array[i][j]+" ");
}
System.out.println(s);
}
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);/*initializing the variable input with
new Scanner object*/
System.out.println("Enter the number of rows");/*getting the number of rows
and columns of the 2D array as an user input*/
int noOfRows=input.nextInt();
System.out.println("Enter the number of columns");
int noOfColumns=input.nextInt();
int newArr[][] = new int[noOfRows][noOfColumns];//creation of the 2D array
for(int i = 0 ; i < noOfRows ; i++) {/*Goal of this for loop is to assign the
userInpts to the array indexes*/
for(int j = 0 ; j < noOfColumns ; j++) {
System.out.println("Enter a number");/*Getting the user inputs to
store in the array*/
newArr[i][j] = input.nextInt();
}
}
for(int i = 0 ; i < noOfRows ; i++) {/*Goal of this for loop is printing the
array and sum of the row at the end of the each row*/
int sumofTheRow = 0;/*This is the variable which holds the sum of the
current row so initial value is 0 */
for(int j = 0 ; j < noOfColumns ; j++) {
sumofTheRow += newArr[i][j];/*so inside the inner for loop sumOfTheRow
will be calculated by adding the elements in the row one by one*/
System.out.print(newArr[i][j] + " ");
}
System.out.println(sumofTheRow);//Calculated sum of the row will be displayed
/*So now if i is less than noOfRows then again it will increment the value of i by one and move to the next row */
}
input.close();/*closing the scanner variable to avoid memory leaks --> [ now garbage collector will free the memory area of scanner object by collecting the scanner object]*/
}
}

Two Dimensional Matrix as Input

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..

Reading Multiple Lines, ArrayList

The problem I wanted to solve is:
Sereja has an array a, consisting of n integers a1, a2, ..., an. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out m integers l1, l2, ..., lm (1 ≤ li ≤ n). For each number li he wants to know how many distinct numbers are staying on the positions li, li + 1, ..., n. Formally, he want to find the number of distinct numbers among ali, ali + 1, ..., an.?
Sereja wrote out the necessary array elements but the array was so large and the boy was so pressed for time. Help him, find the answer for the described question for each li.
I need to be able to read an input like such:
10 10
1 2 3 4 1 2 3 4 100000 99999
1
2
3
4
5
6
7
8
9
10
I tried using buffered reader, but I always get a runtime error
import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(new BufferedInputStream(System.in));
int n = scan.nextInt();
int m = Integer.parseInt(scan.nextLine());
int[] a = new int[n];
int[] l = new int[m];
for(int i=0; i<n-1; i++)
{
a[i] = scan.nextInt();
}
a[n] = Integer.parseInt(scan.nextLine());
for(int j=0; j<m; j++)
{
l[j] = Integer.parseInt(scan.nextLine());
}
int counter = 0;
ArrayList<Integer> list = new ArrayList<Integer>();
for(int k=0; k<m; k++)
{
for(int x=l[k]; x<= n; x++)
{
if(!(list.contains(x)))
{
list.add(x);
counter++;
}
}
System.out.println(counter);
}
}
}
Whenever I run this program, I get a runtime error. The output that I need to get with the aforementioned input is
6
6
6
6
6
5
4
3
2
1
Why isn't it working?
OK, I tried this:
import java.io.*;
import java.util.ArrayList;
public class Main
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] tokens = br.readLine().split(" ");
int n = Integer.parseInt(tokens[0]);
int m = Integer.parseInt(tokens[1]);
String[] tokenstwo = br.readLine().split(" ");
int[] a = new int[n];
int[] l = new int[m];
for(int i=0; i<n; i++)
{
a[i] = Integer.parseInt(tokenstwo[i]);
}
for(int j=0; j<m; j++)
{
l[j] = Integer.parseInt(br.readLine());
}
int counter = 0;
ArrayList<Integer> list = new ArrayList<Integer>();
for(int k=0; k<m; k++)
{
for(int x=l[k]; x<= n; x++)
{
if(!(list.contains(x)))
{
list.add(x);
counter++;
}
}
System.out.println(counter);
}
}
}
It said something about IOException. Therefore, i added the throws ioexception at the top. It still give a runtime error though.
Try using the below code for taking the input. Fit it for your need.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] tokens = br.readLine().split(" ");
int n1 = Long.parseLong(tokens[0]);

Adjacency Matrix java

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.

Categories

Resources