Draw a line in JAVA with Pattern - Beginner - java

I want to draw a line in java. I will use these draws with making Triangles. I can do this :
1***
11**
111*
1111
and i need to do this:
1***
*1**
**1*
***1
Ive done a lot of work today and my mind got really confused.
Can you help me ? Thanks A lot.
EDIT: also my perfect answer should be Implement Bresenham’s line drawing algorithm but i dont understand in wikipedia.
EDIT 2: my grid code :
String [][] matrix = new String [50][50];
for (int row = 0; row < 50; row++){
for (int column = 0; column < 50; column++){
matrix [row][column] = "*";
}
}

public class Test
{
public static void main(String [] args)
{
int size=50;
String[][] matrix= new String [size][size];
for (int i=0; i < size; i++)
{
for (int j=0; j < size; j++)
{
if (i != j)
matrix[i][j]="*";
else
matrix[i][j]="1";
}
}
for (int i=0; i < size; i++)
{
for (int j=0; j < size; j++)
{
System.out.print(matrix[i][j]);
}
System.out.println();
}
}
}
Edit: if it's already filled with * simply make matrix[i][j]="1"; when i equals j, ie if (i==j).

public class MulArray {
public static void main(String[] args) {
/*
* 1*** 1** 1* 1
*/
String[][] grid = new String[5][5];
for (int row = 0; row < grid.length-1; row++) {
for (int column = 0; column < grid[row].length; column++) {
if (row == column) {
grid[row][column] = "1";
} else {
grid[row][column] = "*";
}
}
}
for (int row = 0; row < grid.length-1; row++)
for (int column = 0; column < grid[row].length; column++) {
if (column != 4) {
System.out.print(grid[row][column]);
}
else{
System.out.print("\n");
}
}
}
}

Related

How can I print a two-dimensional array of characters in Java, to create a 20x20 grid?

I am trying to print a 2d array of periods in Java, however, I can not get the formatting correctly. I am able to create a similar layout NOT using a 2d array. However, I will need to be working with a 2d array to finish the project. I have tried using Arrays.deepToString(); but did not find it useful.
My goal is to have a 20x20 grid of periods like this:
** Without the S and the X
My way without using a 2d array:
for (int i = 20; i >= 1; i--) {
for(int j = 1; j <= 20; j++) {
System.out.print(" .");
}
System.out.print("\n");
}
My try using a 2d array:
final int rows = 20;
final int columns = 20;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
board[i][j] = ".";
}
System.out.println(Arrays.deepToString(board));
}
Put the two together?...
public static void main(String[] args) {
final int rows = 20;
final int columns = 20;
String board[][] = new String[rows][columns];
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
board[row][col] = ".";
}
}
display2Darray(board);
}
public static void display2Darray(String[][] arr) {
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[row].length; col++) {
System.out.print(arr[row][col]);
}
System.out.println();
}
}
You have to print your 2D array outside outer loop but you print this 2D array result outside inner loop. After that you have to remove bracket and comma through java replace() method.
Here down is modified code:
import java.util.*;
public class Main
{
public static void main(String[] args) {
final int rows = 20;
final int columns = 20;
String board[][] = new String[rows][columns];
// OUTER LOOP
for (int i = 0; i < rows; i++) {
// INNER LOOP
for (int j = 0; j < columns; j++) {
board[i][j] = ".";
}
}
System.out.print(Arrays.deepToString(board).replace("],", "\n")
.replace(",", "")
.replace("[[", " ")
.replace("[", "")
.replace("]]", ""));
}
}

Not Printing a 2D array

When I call the printBoard method it doesn't print anything. Could't find out what I wrote wrong
How could I fix that if the error is nowhere else.
public class Board {
private int rows;
private int cols;
private char[][] Board = new char[rows][cols];
public Board(int row, int col) {
rows = row;
cols = col;
for (int i = 0; i < Board.length; i++) {
for (int j = 0; j < Board[i].length; j++) {
Board[i][j] = '-';
}
}
}
public void printBoard() {
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.print("|");
}
System.out.println(" ");
}
}
}
You do not recreate Board in the constructor when you set rows and cols, the array is initialized with default 0 values.
It should be:
public Board(int row, int col) {
rows = row;
cols = col;
Board = new char[rows][cols]; // <-- reset array
for (int i=0; i<Board.length ; i++) {
for (int j=0; j<Board[i].length; j++) {
Board[i][j]='-';
}
}
}
You might have assumed that Board array would be initialized with the values set in the constructor, but in fact the constructor is invoked after initializing the instance variables in the order of their appearance in the class definition.

Finding the location of a number in a 2d array

I am trying to create a program that lets you find how many times a curtain number occurs in a 2d array. One of the things that I am required to do is to create a method called countInstence which counts the amount of times a number occurs but also where they are located in the array. the problem i'm having is how do I output the location of the the number
public int[][] createArray(int rSize, int cSize) {
Random rnd = new Random();
int[][] array = new int[rSize][cSize];
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
array[row][col] = rnd.nextInt(26);
}
}
return array;
}
public void print2dArray(int[][] array) {
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
System.out.print(array[row][col] + "\t");
}
System.out.println("\n");
}
}
public int countInstence(int[][] array, int search) {
int count = 0;
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
if (array[row][col] == search)
count++;
}
}
return count;
}
public static void main(String[] args) {
Journal5b call = new Journal5b();
Scanner in = new Scanner(System.in);
int[][] myArray;
int value;
myArray = call.createArray(10, 10);
call.print2dArray(myArray);
System.out.println("Enter a number to search for: ");
value = in.nextInt();
System.out.println("Your number occurred "
+ call.countInstence(myArray, value) + " Times");
}
Just insert a one line print statement inside of the if-statement and format to print the row and column of the current index, as below...
public int countInstance(int[][] array, int search) {
int count = 0;
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
if (array[row][col] == search) {
System.out.printf("Instance found at [%d, %d]\n", row, col);
count++;
}
}
}
return count;
}
If you aren't familiar with the System.out.printf call or the %d symbols, you can read more about it here.
Just add this line to the for loop
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
if (array[row][col] == search) {
System.out.printf("Instance found at [%d, %d]\n", row, col);// add this line
count++;
}
}
}
If you want to also use location at other place then just declare a List and add location to that list while searching for element.
public static List<String> location=new ArrayList<String>();
public int countInstence(int[][] array, int search) {
int count = 0;
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
if (array[row][col] == search)
{
count++;
String loc=row+","+col;
location.add(loc);
}
}
}
return count;
}
public static void main(String[] args) {
Test call = new Test();
Scanner in = new Scanner(System.in);
int[][] myArray;
int value;
myArray = call.createArray(10, 10);
call.print2dArray(myArray);
System.out.println("Enter a number to search for: ");
value = in.nextInt();
System.out.println("Your number occurred "
+ call.countInstence(myArray, value) + " Times");
System.out.println("locations :");
for(int i = 0; i < location.size(); i++) {
System.out.println(location.get(i));
}
}
I suggest using Points:
List<Point> locations=new ArrayList<Point>();
....
if (array[row][col] == search)
{
count++;
locations.add(new Point(row,col));
}

Java program. Adding Matrices

So in my code, I am supposed to add together two matrix objects using this notation m1.add(m2) where m1 is and m2 are objects and add is the method being invoked. This is what my code looks like right now. I have one constructor that generates a matrix when an object in the main method is created. Whenever I try to run the program in the main method, it gives me an error. I have to essentially take a matrix object and add it with another matrix object. Note the matrix object is created and run through the constructor first.
import java.util.Arrays;
public class matrix {
int row;
int column;
static int[][] matrix;
matrix(int row, int column) {
this.row = row;
this.column = column;
if (row < 1 || column < 1) {
this.row = 1;
this.column = 1;
}
if (row > 5 || column > 5) {
this.row = 5;
this.column = 5;
}
this.matrix = new int[this.row][this.column];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = (int) (Math.random() * 21) - 10;
}
}
toString(matrix);
}
public static void toString(int[][] matrix2) {
// for loop and prints each indexed variable using the system.out.print
// method.
for (int i = 0; i < matrix2.length; i++) {
System.out.print("\n");
for (int j = 0; j < matrix2[0].length; j++) {
System.out.printf("%5d", matrix2[i][j]);
}
System.out.print("\n");
}
}
public static void add( int[][] B)
{
int[][]sumMatrix = new int[matrix.length][B[0].length];
for(int i =0; i < matrix.length; i++)
{
for(int j=0; j < matrix[i].length;j++)
{
sumMatrix[i][j] = matrix[i][j] + B[i][j];
}
}
toString(sumMatrix);
}

java performing array calculation [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
The code below will print two square matrices and I need them to perform multiplication between the two matrices but i cant seem to get that part working. I put a comment right before that block of code where the problem is. But for now all it prints is zeros. Iv been looking online at a lot of sites but cant seem to get mine to work.
import java.util.*;
import java.math.*;
public class Main {
public static void main(String[] args) {
//create the grid
final int rowWidth = 9;
final int colHeight = 9;
Random rand = new Random();
int [][] board = new int [rowWidth][colHeight];
//fill the grid
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
board[row][col] = rand.nextInt(10);
}
}
//display output
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();
}
System.out.println();
}
System.out.println();
int [][] board2 = new int [rowWidth][colHeight];
//fill the grid
for (int row2 = 0; row2 < board2.length; row2++) {
for (int col2 = 0; col2 < board[row2].length; col2++) {
board[row2][col2] = rand.nextInt(10);
}
}
//display output
for(int m = 0; m < board2.length; m++) {
for(int n = 0; n < board[m].length; n++) {
System.out.print(board[m][n] + " ");
}
System.out.println();
}
//error is somewhere here
int[][] calculationMultiplication = new int[rowWidth][colHeight];
for (int l = 0; l < rowWidth; l++) {
for (int t = 0; t < colHeight; t++) {
for (int z = 0; z < rowWidth; z++) {
calculationMultiplication[l][t] = calculationMultiplication[l][t] + board[l][z] * board2[z][t];
}
}
}
//display output
System.out.println("\nProduct of the 2 matrices is ");
for (int i = 0; i < calculationMultiplication.length; i++) {
for (int j = 0; j < calculationMultiplication[0].length; j++) {
System.out.print(calculationMultiplication[i][j] + " ");
}
System.out.println();
}
} //end of main
} //end of class Main
The problem is that you've not filled the board2 array, so all its elements will be 0. In the for loop, you should also assign random values to board2. You are doing it twice for the board array.
//fill the grid
for (int row2 = 0; row2 < board2.length; row2++) {
for (int col2 = 0; col2 < board2[row2].length; col2++) { // notice 'board2[row].length'
board2[row2][col2] = rand.nextInt(10);
}
}
You should do something similar in the for loops where you display the array:
//display output
for (int m = 0; m < board2.length; m++) {
for (int n = 0; n < board2[m].length; n++) { // notice 'board2[row].length'
System.out.print(board2[m][n] + " ");
}
System.out.println();
}
board2 is always zero.
You fill the wrong array here:
//fill the grid
for (int row2 = 0; row2 < board2.length; row2++) {
for (int col2 = 0; col2 < board[row2].length; col2++) {
board[row2][col2] = rand.nextInt(10);
}
}
Basically you just did simple copy paste mistakes that can be avoidable if you used methods. I'll tell you how but first here's how you can discover your mistake:
System.out.println(String.format("%d * %d = %d",board[l][z], board2[z][t], board[l][z] * board2[z][t]));
Add this just before doing the calculation for calculationMultiplication[l][t]. Try if you want...
Anyway getting back to your mistakes, you have populated your first matrix only, the second one contain zeros (verify your code in the for loop for inserting random numbers into the second matrix), therefore any number multiplied by zero is equal to zero.
I haven't looked at all your code, because it contain a lot of copy paste which confused you and could confuse any one as well, so here's a better way to avoid mistakes in printing the matrix and inserting random numbers:
Printing:
void printMatrix(int[][] matrix){
for(int row =0; row < numOfRows; row++){
for(int col =0; col < numOfCols; col++){
System.out.print(matrix[row][col]+" ");
}
System.out.println(); // new line
}
}
Inserting:
void insertMatrix(int[][] matrix){
for(int row =0; row < numOfRows; row++){
for(int col =0; col < numOfCols; col++){
matrix[row][col] = rand.nextInt(10); // rand must be declared outside any method
}
}
}
Putting all together:
import java.util.*;
public class Main {
// create the grid
final static int rowWidth = 9;
final static int colHeight = 9;
static Random rand;
public static void main(String[] args) {
rand = new Random();
int[][] board = new int[rowWidth][colHeight];
int[][] board2 = new int[rowWidth][colHeight];
int[][] calculationMultiplication = new int[rowWidth][colHeight];
// fill
insertMatrxi(board);
// display output
printMatrix(board);
System.out.println();
// fill
insertMatrxi(board2);
// display output
printMatrix(board2);
for (int l = 0; l < rowWidth; l++) {
for (int t = 0; t < colHeight; t++) {
for (int z = 0; z < rowWidth; z++) {
calculationMultiplication[l][t] += board[l][z] * board2[z][t];
}
}
}
// display output
System.out.println("\nProduct of the 2 matrices is ");
printMatrix(calculationMultiplication);
} // end of main
public static void printMatrix(int[][] matrix) {
for (int row = 0; row < rowWidth; row++) {
for (int col = 0; col < colHeight; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println(); // new line
}
}
public static void insertMatrxi(int[][] matrix) {
for (int row = 0; row < rowWidth; row++) {
for (int col = 0; col < colHeight; col++) {
matrix[row][col] = rand.nextInt(10);
}
}
}
} // end of class Main

Categories

Resources