I am writing a code to indicate open and closed elements in a 2d array. An open element is represented with . and a closed element is represented with *. The first column in the array must be completely open whereas all the other columns must be closed. The output should be:
.**
.**
.**
The array is also going to vary in size as the user will determine how big the array is. I have managed to code a 2D array grid as this is not hard, however, I am trying to now use an if-statement to make the first column all open. I placed the if-statement within the nested loop:
import java.util.Arrays;
import java.util.Scanner;
public class trial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("What size square grid do you want? ");
int m = sc.nextInt();
char[][] grid = new char[m][m];
int i;
int j;
for(i=0; i<grid.length; i++) {
for(j=0; j<grid[i].length; j++) {
grid[i][j] ='.';
if(grid[j].length > grid[0].length) {
System.out.println("");
}else {
System.out.print('*');
}
StdOut.print(grid[i][j]);
}
StdOut.println();
}
}
}
This, however, is giving me an output that looks like this:
*.*.*.
*.*.*.
*.*.*.
*.*.*.
I have tried placing the if-statement outside of this nested for-loop but I then get an error with my variables as they have not been defined. Any assistance as to how to fix this or make it that I can get values for my i and j variables outside of the for-loop would be greatly appreciated.
I slightly modify your code to make it fit the description.
i and j will vary when the loop proceeds, and should be accessed inside the loop only.
It seems that you want to change the content inside grid, which can be accessed outside the loop after processing.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("What size square grid do you want? ");
int m = sc.nextInt();
char[][] grid = new char[m][m];
int i;
int j;
for (i = 0; i < grid.length; i++) {
for (j = 0; j < grid[i].length; j++) {
grid[i][j] = '.';
if(j > 0) {
grid[i][j] = '*';
}
System.out.print(grid[i][j]);
}
System.out.println();
}
// you cannot access i/j outside the loop scope. instead, you can access the grid
System.out.println("Loaded array:");
Arrays.stream(grid).forEach(System.out::println);
}
Just check if the current column is 0 or not
Just a minor change will work here
I am writing only the main loop below
for(i=0; i<grid.length; i++) {
for(j=0; j<grid[i].length; j++) {
if(j == 0){ //0th column make it dot(.)
grid[i][j] ='.';
}
else { //For other columns put asterisk(*)
grid[i][j] = '*';
}
}
}
Here's a different way to think about 2D arrays. They are simply a 1D array where each element is itself another 1D array (a complete "row").
With that in mind, here's a different way to initialize and print the contents of the 2D array using a mixture of enhanced and indexed for loops:
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("What size square grid do you want? ");
int m = sc.nextInt();
char[][] grid = new char[m][m];
for(char[] row : grid) {
for(int col=0; col<row.length; col++) {
row[col] = (col == 0) ? '.' : '*';
}
}
for(char[] row : grid) {
for(char c : row) {
System.out.print(c);
}
System.out.println();
}
}
Output:
What size square grid do you want?
5
.****
.****
.****
.****
.****
Related
I'm trying to figure out how to print out a second array that is based off my first one but only displays values that are greater than the value to its left and less than the value to it's right and displaying these values by row in the row that they are in the original array. Here's my code so far.
public static void main(String[] args)
{
int row, col, i, j;
int arr[][] = new int[10][10];
Scanner scan = new Scanner(System.in);
row = 3;
col = 6;
// enter array elements.
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
System.out.println("Enter a value: ");
arr[i][j] = scan.nextInt();
}
}
// the 2D array is here.
System.out.print("Matrix Display :\n");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
System.out.print(arr[i][j]+ " ");
}
System.out.println();
}
System.out.println(arr[0]);
System.out.println(arr[1]);
System.out.println(arr[2]);
System.out.println(arr[3]);
}
}
You won't know how many of the elements fit your criteria, so you need to use a mutable object. Since each row might have a different number of matching numbers, you won't be able to make a normal array without null values in it most of the time.
Use a 2D ArrayList, scan through your original 2D array, and add the value that match your criteria to the corresponding row of your ArrayList.
You could do something like this:
int width = arr[0].length-1;
ArrayList<ArrayList<Integer>> listoflists= new ArrayList<ArrayList<Integer>>();
// Scan array for matching values
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
listoflists.add(new ArrayList<Integer>());
if(j==0 && arr[i][0]<arr[i][1])
listoflist.get(i).add(arr[i][0]);
else if(j==width && arr[i][width]>arr[i][width-1]
listoflist.get(i).add(arr[i][width]);
else if( #this is the last condition to check from both sides)
listoflist.get(i).add(arr[i][j]);
}
}
I am trying to write a program that will ask the user for a size of a square and then print out a square that has that many *'s.
For example,
Size?
3
Then it prints out a 3 x 3 square of *'s.
I need to also use for and while loops.
Thanks
Working code :
import java.util.Scanner;
public class patternBox {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
System.out.println("Enter number of row / column : ");
int row = input.nextInt(); // take user input
for (int i = 0; i < row; i++) { // outer loop for row change
for (int j = 0; j < row; j++) // inner loop for * print
{
System.out.print("*");
}
System.out.println();
}
}
}
Read: How to get input from user using Scanner
Im not asking for the answer per say im asking necessarily what would i need to change in order to print out sections of a 2d array for example if the array has 5 rows and 5 columns how would i print out the last 3 rows and last three columns.
import java.util.Scanner;
public class multiplication {
static int a,b;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
a =input.nextInt();
b = input.nextInt();
int[][] matrix = new int[a][b];
matrix = timesTable(a,b);
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(" "+matrix[row][column] + "\t|");
}
System.out.println();
}
}
public static int[][] timesTable(int r, int c)
{
int [][] yes = new int[c][c];
for ( r = 0; r < yes.length ; r++)
{
for (c = 0; c < yes[r].length; c++)
{
yes[r][c] = (r+1)*(c+1);
}
}
return yes;
}
}
if((row = 0 && col > 1) ||( row > 1 && col != 1)) {
//print
}
This logic should work for your example. But I don't understand what you're trying to do.
Can you try explain a bit more what you want to do ?
Edit: you might wanna check this. Oracle documentation bottom of the page with arraycopy and arraymanipulation
Is the goal of this exercise to build the matrix and then print the matrix -or- do you simply need to display the desired output? I assume this is a class assignment.
Hint: Think about this .. if you enter 2 & 5, do you want a 2x5 matrix or a 4x4 matrix? It's important when you alloc your matrix size.
I start learning programming about 4 days ago by myself and iam a lil bit stuck with 2d arrays. I try to challenging myself with tasks, like get from 2d array column with most zeros or atleast just count zeros, so far i get this far
public class b {
public static void main(String[] args) {
int a[][] = new int [5][5];
int i,j;
int s = 0;
for(i= 0;i<a.length; i++)
for(j = 0; j<a[i].length; j++){
a[i][j] = (int)(Math.random()*10);
}
for(i=0;i<a.length;i++){
for(j=0;j<a[i].length;j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
for(j=0;j<a[0].length;j++) {
for(i=0;i<a.length;i++) {
if(a[i][j] >-1 || a[i][j]<1) {
s++;
System.out.println(s +"\t");
s = 0;
}
}
}
}
}
Can somebody explain me why result is always 1 and why it counts columns and rows in one row?
Suppose the condition enters into if(a[i][j] >-1 || a[i][j]<1) then you increase s by 1 then print it which gives 1 then you reassign it to s=0 so it gives same 1 each time.So remove the s=0 and place the printing line after end of loop
public class b {
public static void main(String[] args) {
int a[][] = new int [5][5];
int i,j;
int s = 0;
for(i= 0;i<a.length; i++)
for(j = 0; j<a[i].length; j++){
a[i][j] = (int)(Math.random()*10);
}
for(i=0;i<a.length;i++){
for(j=0;j<a[i].length;j++)
System.out.print(a[i][j] + "\t");
System.out.println();
}
for(j=0;j<a[0].length;j++){
for(i=0;i<a.length;i++)
if(a[i][j] >-1 && a[i][j]<1){
s++;
}
System.out.println("Zero in column no. "+j+" is "+s +"\t");
s=0;
}
}
}
Demo
Result will be 1 because you're re-assigning 0 to s everytime. But the issue is not only that.
Firstly your condition is using wrong indices. Instead of a[i][j] you should use a[j][i] as you're traversing column-wise. Secondly:
if(a[j][i] >-1 || a[j][i]<1){
can be simply written as:
if(a[j][i] == 0) {
So the structure is the outer for loop will iterate over each column number. And for each column number, inner for loop will find count of 0. You've to maintain a max variable outside both the loops, to track the current max. Also, you've to use another variable inside the outer for loop to store the count for current column.
Everytime the inner for loop ends, check if current column count is greater than max. If yes, reset max.
int max = 0;
for(j=0;j<a[0].length;j++){
int currentColumnCount = 0;
for(i=0;i<a.length;i++) {
if(a[j][i] == 0) {
currentColumnCount++;
}
}
if (currentColumnCount > max) {
max = currentColumnCount;
}
}
I am trying to find the longest series of horizontal O's in my 2d array and just print out the longest path. I don't see my logic error, I keep reading over this but don't see my error. I have been stuck here for about 2 days. I am thinking maybe there is something wrong with my finding max length statement? I get an out of bounds error on line 58 and 31. Any advice to what I'm doing wrong would be much appreciated.
public class game {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner kbd = new Scanner(System.in);
System.out.println("ENTER A SINGLE INTEGER: ");
int n = kbd.nextInt();
char[][] mazeValue = new char[n][n];
System.out.println("ENTER A PATH: ");
for(int i = 0; i < mazeValue.length; i++ ){
for(int j = 0; j< mazeValue[i].length; j++){
mazeValue[i][j]= kbd.next().charAt(0);
}
}
printMaze(mazeValue);
horizontalPath(mazeValue);
}
public static void printMaze(char mazeValue[][])
{
System.out.println("MAZE");
for(int i = 0; i < mazeValue.length; i ++)
{
for (int j = 0; j < mazeValue[i].length; j++)
{
System.out.printf("%4c",mazeValue[i][j]);
}
System.out.printf("\n");
}
}
public static void horizontalPath(char mazeValue[][])
{
int horizontalPath=0;
int maxHorizontalCount=0;
int i;
int j;
for(i= 0; i<mazeValue.length; i++){
for(j = 0; j<mazeValue[i].length; j++){
if(mazeValue[i][j]== 'o'){
horizontalPath = horizontalPath + mazeValue[i][j];
}
}
if(horizontalPath < mazeValue[i][j])
maxHorizontalCount = mazeValue[i][j];
}
System.out.printf("Longest horizontal path row %d length %d",i,maxHorizontalCount);
}
}
I'm guessing you have some imports before your code which offsets the line numbers, and your problem is in line 47 in the code above:
if(horizontalPath < mazeValue[i][j])
maxHorizontalCount = mazeValue[i][j];
This block is outside of your for loop over j. This means that by the time control gets here, j will be equal to n, thus causing an index out of bounds.
Also note you're not actually computing a max value of anything, just setting maxHorizontalCount to the value at [i][j]. To compute a max, you should do something like
maxHorizontalCount = maxHorizontalCount > mazeValue[i][j] ? maxHorizontalCount : mazeValue[i][j];
or use Math.max() of course.