I haven't used 2D Arrays before so apologies for any 'obvious statements'.
I want to create a 2D Array for a 15 by 20 'table' and want the following to be applied:
I want each row to be a separate Array.
I want each row to have random 0's and 1's generated
The code I have created creates the 15 x 20 table but not sure if each row is an Array and can't figure out how to put random 0's and 1's. Help would be appreciated! Thanks!
for (int i=0; i < ar.length; i++) {
for (int j=0; j < ar[i].length; j++) {
ar[i][j] = 0;
System.out.print(" " + ar[i][j]);
}
System.out.println("");
}
Like this?
int cols = 15;
int rows = 20;
Random rand = new Random();
int[][] myArray = new int[rows][cols];
for (int i=0; i < myArray.length; i++) {
for (int j=0; j < myArray[i].length; j++) {
myArray[i][j] = rand.nextInt(2);
System.out.print(" " + myArray[i][j]);
}
System.out.println("");
}
Read more here
Use nextInt method.
myArray[i][j] = rand.nextInt(2); // we are using 2 cause nextInt generates random number between 0 to 2 exclusive.
Related
I want to print out my array first then the summation of each row, after my full array, using a nested for loop. But, it seems that nothing else happens after my first nested for loop that assigns values to my 2D array. I want it to look like:
The sum of the 1st row is: ...
The sum of the 2nd row is ... and so on until the last row.
Here is what I have so far.
My code:
public class RowsSum {
public static void main(String[] args) {
int num = 1;
int[][] nums = new int[5][3]; //declaring a 2D array of type int
for (int i = 0; i <= nums.length; i++) {
for (int j = 0; j < nums[0].length; j++) {
num *= 2;
nums[i][j] = num;
System.out.print(nums[i][j] + "\t");
}//closing inner loop
System.out.println("");
}// closing nested for loop
int sum = 0;
int row = 0;
for (int i = 0; i <= nums.length; i++) { //second nested for loop
row++;
for (int j = 0; j < nums[0].length; j++) {
sum = sum + nums[i][j];
}//closing inner loop
System.out.println("The sum of the " + row + "is" + sum + "\t");
System.out.println("");
}// closing nested for loop
}// closing main method
}//closing class
You are not re-initializing the sum variable to 0 before traversing through the row. Also, it's not clear what your second double for-loop is trying to accomplish with this code:
num *= 2;
nums[i][j] = num;
This repeated code is actual altering the values in the array, you should remove it, it is causing unwanted effects.
Adjust to this:
for (int i = 0; i <nums.length; i++){ //second Outer loop
sum = 0;
for (int j = 0; j < nums[0].length; j++){
sum = sum + nums[i][j];
}//closing inner loop
System.out.println("The sum of row " + (i+1) + " is " + sum);
}
Also, the nested for-loops are in fact the inner loops not the outer loops.
EDIT: You are actually also accessing outside of the bounds of the original array, specifically in the outer loops. You have this:
for (int i = 0; i <= nums.length; i++)
Change it to this:
for (int i = 0; i < nums.length; i++)
Note the small change of <= to <, its subtle yet important since arrays are 0 indexed in java so in an array of length 5, the maximum index will be 4.
How to make square matrix appear in a "snake" pattern? User inputs # of rows/columns in array and then matrix is displayed in ascending order but in a snake pattern.
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13
import java.util.Scanner;
public class A3_Q2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
System.out.println("[-------------------------]");
System.out.println("[ Array Pattern ]");
System.out.println("[-------------------------]");
System.out.println("How many rows/columns do you want your array to have? (Mist be at least 3):");
int arraySize = keyboard.nextInt();
while(arraySize < 3)
{
System.out.println("Lets try this again ....");
System.out.println("How many rows/columns do you want your array to have? (Mist be at least 3):");
arraySize = keyboard.nextInt();
}
int [][] pattern = new int[arraySize][arraySize];
int number = 1;
for (int i = 0; i <= arraySize -1; i++){
for(int j = 0; j <= arraySize - 1; j++)
{
pattern[i][j] = number;
number++;
System.out.printf("%3d", pattern[i][j]);
}
System.out.println("");
}
}
}
If we wanted to just print the 2D array in ascending order from left to right on each row, we could just use the following for loop:
for (int i=0; i < arraySize; ++i) {
for (int j=0; j < arraySize; ++j) {
System.out.printf("%3d", pattern[i][j]);
}
}
To get the reverse order effect you want, we only need to add logic such that for odd rows, we print a row backwards, from left to right:
for (int i=0; i < arraySize; ++i) {
if (i%2 == 0) {
// for even rows, print as we normally would
for (int j=0; j < arraySize; ++j) {
System.out.printf("%3d", pattern[i][j]);
}
}
else {
// for odd rows, iterate backwards over the array, the print left to right
for (int j=arraySize-1; j >= 0; --j) {
System.out.printf("%3d", pattern[i][j]);
}
}
System.out.println();
}
Update:
You can initialize your array using something like the following:
int arraySize = 4;
for (int i=0; i < arraySize; ++i) {
for (int j=0; j < arraySize; ++j) {
pattern[i][j] = i*arraySize + j + 1;
}
}
I have an x by y board of numbers stored in a two dimensional array in java that I would like to print out to the user in a nice formatted manner. Would there be an easy way to do this in java?
Here is how I build my board:
board = new int[TotRow][TotCol];
You might prefer the one line, because it's easy, Arrays.deepToString(Object[]) the Javadoc says (in part),
This method is designed for converting multidimensional arrays to strings.
System.out.println(Arrays.deepToString(board));
If you want the number to be padded properly as well use String.format(),
for (int i = 0; i < TotRow; i++) {
for (int j = 0; j < TotCol; j++) {
System.out.print(String.format("%3d", board[i][j]) + "\t");
}
System.out.println();
}
Notice that I have used %3d for formatting, you can use format as required by you
You can print the board two dimensional array like this
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + "\t");
}
System.out.println();
}
Since I don't like relying on tabs, I'd like to mention some approaches that don't rely on them.
If you know that all of the numbers in the table are nonnegative numbers of, say, 4 digits or less, you can use String.format in a manner similar to Nitin's answer:
for (int i = 0; i < TotRow; i++) {
for (int j = 0; j < TotCol; j++) {
System.out.print(String.format("%4d ", board[i][j]));
}
System.out.println();
}
The %4d means to format the number using a width of 4 characters, and pad with blanks on the left if the number takes fewer than 4 characters to print. Thus, if there aren't any 5-digit or longer numbers, each print will print exactly 5 characters--a 4-character field for the number, and a space after the number. This will make everything line up, as long as none of the numbers is too large. If you do get a number that takes more than 4 characters, the formatting will get messed up.
Here's a way to adjust the column width so that it's just large enough to hold all the values in the table, and works fine if there are negative numbers:
int maxWidth = 0;
for (int i = 0; i < TotRow; i++) {
for (int j = 0; j < TotCol; j++) {
maxWidth = Math.max(maxWidth, Integer.toString(board[i][j]).length());
}
}
String format = "%" + maxWidth + "d ";
for (int i = 0; i < TotRow; i++) {
for (int j = 0; j < TotCol; j++) {
System.out.print(String.format(format, board[i][j]));
}
System.out.println();
}
Note: not tested
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
System.out.print(board[i][j] + "\t");
}
System.out.println();
}
You basically just use a nested loop.
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
i have a code that create 2d array by asking user to enter the input than the system check if the elements are prime or not and if they are prime the system will copy them to an 1d array.
i can create the 2d array but i am stuck in the checking on the prime number and copied to a second array
this is the code
package question6;
import java.util.Scanner;
public class MtrixPrime {
public static void main(String[] args) {
int rows;
int cols;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of row");
rows = sc.nextInt();
System.out.println("Enter number of column");
cols = sc.nextInt();
int[][] matrix = new int[rows][cols];
int[] array = new int[rows];
System.out.println("Enter numbers in the matrix");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if(matrix[i][j] % matrix[i][j] ==0 && matrix[i][j] %1 == 0){
////here i am stuck can anyone help me ??
array[i * j];
}
matrix[i][j] = sc.nextInt();
}
}
for(int row = 0 ;row<matrix.length; row++){
for(int col = 0 ; col< matrix.length; col++){
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
}
}
I know it's old post but this might help others.
Used isPrime a boolean flag to save the state of matrix[i][j] value.
If reminder is 0 isPrime will hold false state of matrix[i][j].
Everything is similar like finding prime number of single number. Just have to use 3 for loops for matrix index, before that I have taken matrix values separately.
here's the code.
public static void main(String[] args) {
int rows, cols, remainder;
boolean isPrime = true;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of row and colums : ");
rows = sc.nextInt();
cols = sc.nextInt();
int[][] matrix = new int[rows][cols];
System.out.println("Enter numbers in the matrix");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
matrix[i][j] = sc.nextInt();
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
for (int k = 2; k <= matrix[i][j] / 2; k++) {
remainder = matrix[i][j] % k;
if (remainder == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(matrix[i][j] + " is a Prime number");
} else
System.out.println(matrix[i][j] + " is not a Prime number");
}
}
}
One tricky thing to look out for is that since you don't know how many primes you're going to get, and you're using regular arrays, you need a 1d array at least the total size of your 2d array, or you should just use an ArrayList. If you're set on using a primitive array, you could just add a counter that increases every time you find a new prime, and use that counter value as your index. This however would leave you with zeros on the back end of your array. If you want your index to correspond to the multi-dimensional array index, you multiply the row index by the number of members in the row, and then add the column index in order to get a 1d index as shown below. This would leave you with zeros inbetween elements in your array. Having zeros shouldn't necessarily be a bad thing since it isn't prime, but its still way easier in my mind to use an ArrayList.
int[][] nums2d = {{0,1,2},{3,4,5},{6,7,8}};
int[] nums1d = new int[9];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int index = i * 3 + j;
nums1d[index] = nums2d[i][j];
}
}
I want to read the following into a 2d jagged array:
3
7 4
2 4 6
8 5 9 3
I need to increase the column size on every input. I'm not exactly sure how to do it.
My code is as follows:
int col = 1;
int[][] values = new int[rows][col];
for(int i = 0; i < values.length; i++){
for(int j = 1; j < col; j++)
{
values[i][j] = kb.nextInt();
col++;
}
}
This should do it.
int[][] values = new int[rows][];
for(int i = 0; i < values.length; i++)
{
values[i] = new int[i+1];
for(int j = 0; j < values[i].length; j++)
{
values[i][j] = kb.nextInt();
}
}
Basically, you start by defining how many rows your 2d array should have.
In the for loop, you define the 1d array for each row with its length.
Sample
// don't fix the second dimension
int[][] values = new int[rows][];
for(i = 0; i < rows;i ++){
//column size increases for every line input
values[i] = new int[i+1];
for(j = 0; j < values[i].length; j++) {
values[i][j] = kb.nextInt();
}
}
In Java, arrays do not have to be strictly rectangular. The variable values is a rows-element array of references to int arrays. Here, values[0] is a 1-element int array, values[1] is a 2-element int array, etc.