Multidimensional arrays from standard input - java

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

Related

Creating user input for randomized 2D java array issue - OutOfBoundsException

Trying to create a 2D array that takes the users input for rows and columns. The numbers inside the array are then randomized from 0 to 100. I am getting the following error:
Enter rows for the array: 3
Enter columns for the array: 2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at test2.main(test2.java:17)
Here is my code:
import java.lang.Math;
import java.util.Scanner;
public class test2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter rows for the array: ");
int rows = scan.nextInt();
System.out.print("Enter columns for the array: ");
int columns = scan.nextInt();
int [][] myArray = new int [rows][columns];
for (rows = 0; rows < myArray.length;rows++) {
for (columns = 0; columns < myArray.length; columns++)
myArray[rows][columns] = (int) (Math.random()*100);
System.out.print(myArray[rows][columns] + "\t");
}
}
}
You should use separate variables to run the loops.
public class Random {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter rows for the array: ");
int rows = scan.nextInt();
System.out.print("Enter columns for the array: ");
int columns = scan.nextInt();
int[][] myArray = new int[rows][columns];
for (int row = 0; row < rows; row++) {
for (int col = 0; col < columns; col++) {
myArray[row][col] = (int) (Math.random() * 100);
System.out.print(myArray[row][col] + "\t");
}
}
}
}

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

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

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

how to automatically populate a 2d array with numbers

Hi i am trying to auto populate a 2d array based on user input.
The user will enter 1 number, this number will set the size of the 2d array. i then want to print out the numbers of the array.
for example , if the user enters the number 4 . the 2d array will be 4 rows by 4 colums, and should contain the number 1 to 16, and print out as follows.
1-2-3-4
5-6-7-8
9-10-11-12
13-14-15-16
But i am struggling to think of the right statement that will do this.
for the moment my code just prints out a 2d array containing *.
Has anyone any ideas how i could print out the numbers , i'm really stuck.
my code follows:
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter room length");
int num1 = input.nextInt();
int num2 = num1;
int length = num1 * num2;
System.out.println("room "+num1+"x"+num2+"="+length);
int[][] grid = new int[num1][num2];
for(int row=0;row<grid.length;row++){
for(int col=0;col<grid[row].length;col++){
System.out.print("*");
}
System.out.println();
}
}
Read n value,
int[][] arr = new int[n][n];
int inc = 1;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
arr[i][j] = inc++;
Well, first of all you have to fill the array with the numbers. You can use your double for loop for this and a counter variable which you increment after each loop of the inner for loop.
int counter = 1;
for(int x = 0; x < num1; x++)
{
for(int y = 0; y < num2; y++)
{
grid[x][y] = counter++;
}
}
Afterwards you can output the array again with a double for loop.
I am not sure if I understand you right.
You have problem with the code printing *?
If yes, then the reason for that is this
System.out.print("*");
Should be
System.out.print(grid[row]);
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter room length");
int arraySize = input.nextInt();
System.out.println("Length: " + (arraySize*arraySize));
int[][] array = new int[arraySize][arraySize];
int count = 1;
for (int i=0;i<arraySize;i++) {
for (int j=0;j<arraySize;j++) {
array[i][j] = count;
if (j != (arraySize-1))
System.out.print(count + "-");
else
System.out.println(count);
count++;
}
}
}
This code should print out the numbers how you want them.

Categories

Resources