I'm trying to code a method which draws a cross in JAVA. (see the photo for an example).
Here is the example:
Few Questions:
how do I give an array the dimensions via parameter? It seems that Eclipse needs a number instead of variables for the array dimensions. I thought it is possible to give the method a parameter, how big the dimensions of the array should be.
Don't get the idea how to tell the loop which one of the array positions should be an X and which one not.
Here is my code idea so far...it does not really what it should do :) I took "1" instead of "X", so I can do it with an int array.
public void drawCross(int number){
int i,j;
int array[][]=new int[40][40];
for(j=1;j<=number;j++){
for(i=1;i<=number;i++){
if(array[i]==array[j]){
array[i][j]=1;
System.out.print(array[i][j]+" ");
}
}
System.out.print("\n");
}
}
Thank you in advance.
Pete
As this does not really seem homework, the solution
int[][] array = new int[number][number];
for (int i = 0; i < number; i++){
for (int j = 0; j < number; j++){
if (i == j || i == number - 1 - j) {
array[i][j] = 1;
}
System.out.print(array[i][j] + " ");
}
System.out.print("\n");
}
int[][] a is the conventional way. int a[][] is syntactic sugar for C programmers.
In math i normally is the row, and j the column, so switched the for-loops.
Arrays are indexed from 0.
The condition should say whether one is on one of both diagonals, so only concerns the indices i and j.
|| is OR, and && is AND (should you not already know).
As you see, the matrix array is not needed
So:
boolean isOnDiagonal = i == j || i == number - 1 - j;
System.out.print(isOnDiagonal ? "X " : ". "); // if-then-else operator.
Related
I need to create a Method that has 2 parameters in Java, upperborder and lowerborder. This method must create an array from the number 2 to the number 10.
Then I must implement another method, that calculates the factorial for a given number.
Then I must implement a third method that calculates the factorial for every element in the created array and test all these methods in a TestClass.
I know how to do this, but apparently I'm making some kind of a mistake in my code and it gives me the StackOverflow exception. I read the code a couple of times, but I can't seem to quite understand where I'm wrong.
package fakultaetinarray;
public final class FakultaetinArray{
private int i;
private int[] a;
private int j;
public FakultaetinArray(){
System.out.println("Given array : ");
createArray(1, 9);
System.out.println("Factorial for every element : ");
FakinArray();
}
public int fakRe(int n){
if(n == 1){
return n;
}
return n * fakRe(n - 1);
}
public void createArray(int untergrenze, int obergrenze){
this.a = new int[obergrenze];
for(this.j = 1; j <= a.length; j++){
a[i] = j + 1;
System.out.println(a[i]);
}
}
public void FakinArray(){
a[0] = 2;
for(i = 1; i < a.length; i++){
int fak = fakRe(a[i]);
a[i] = fak;
System.out.println(fak);
}
}
}
The reason you're getting StackOverflowErrors is due to your recursive method not having a case when n == 0.
The reason that your values are coming in as 0 is due to how you're constructing your loop.
for(this.j = 1; j <= a.length; j++){
a[i] = j + 1;
System.out.println(a[i]);
}
It's unclear why you're using j here at all, and i is initialized to its default value of 0, so in all reality, you're only ever filling one element of your array with a positive value and all of the others are at zero.
You need to reconsider how your loops are constructed. I would strongly encourage you not to make them fields, but declare them as part of the loop construct instead.
if(n == 1){ is not a strong enough condition to block the recursion: n can go below 1. In your particular case, you have a situation where n is 0.
Consider unwinding the recursion to a simple loop in any case. As a rule of thumb, recursion is not good for O(N) stuff.
I'm having trouble with user input in java, hope anyone can help :)
The user declares how big the 2d array will be(number d is the side of the square array), then inputs a number "n", which tells the program how many inputs of numbers there will be, and then needs to input these numbers (eg. if n=4, the input must be sth like : 5 17 3 20.
I have already written the same thing for a single row array
for(i=0;i<=n;i++) {
arr[i]=sc.nextInt();
}
but am having trouble doing basically the same for the 2d array.
Any ideas?
Use two nested loops and index like arr[i][j]
int d=sc.nextInt(); //length of rows and columns
int n=sc.nextInt(); //user input how many numbers
int[][] array=new int[d][d]; //length and heigth of array
for (int i=0;i<d;i++) {
for(int j=0;j<d;j++) {
array[i][j]=sc.nextInt();
}
}
int distance=0;
int c=0;
for(int i=0;i<d;i++){
for(int j=0;j<d;j++){
array[i][j]=c;
c++;
}
}
that in the end is sth else, I just wanted for the whole thing to be seen, if maybe I missed something elsewhere.
Sorry I don't have the ability to comment yet so I am posting this as an answer. Essentially you need to use a nested for loop as stated above. I will provide you a basic template
for (int i = 0; i < length; i ++){
for (int j = 0; j < width; j ++){
if (counter < userInput){
counter++;
arr[i][j] = value;
} else {
break;
}
}
}
I'm trying to make a program that will make square matrices based on user input. I know that arrays exist, but I wanted to make a matrix from scratch so that I could better understand the basic concept of it and further extend my understanding of loops. So far I have been able to make a square matrix that will accept one number as an input into that matrix, for example I input a square 2x2 matrix and while I want it to look like this 1 2 3 4 with 1 and 2 being above 3 and 4. I have only gotten it to accept one user input that it places in all four slots. For example, if my user input is 1 then the matrix looks like this 1 1
1 1
My code looks like this thus far:
int number;
System.out.println("What are the dimensions of the matrix?");
number = in.nextInt();
for (int k = 0; k < number; k = k +1)
{
System.out.println("What are the numbers in your matrix?");
int matrix_number = in.nextInt();
for (int i = 0; i < number; i = i + 1)
{
for (int j = 0; j < number; j = j + 1)
{
System.out.print(matrix_number);
}
System.out.println();
}
}
I believe that my problem lies in my first for loop where I have the user input the matrix number. Any helpful suggestions on how I can better write this so that the user can input a different number for each slot in the matrix?
It looks like you are trying to create a matrix and then populate it with values read from the user.
To create an N x N matrix of integers
int[][] matrix = new int[n][n]();
To assign a value to a matrix cell [i, j]:
matrix[i][j] = someValue;
Obviously, if you want to read a different value for each cell, you need to call nextInt() multiple times; i.e. once for each value you want to read.
(Note to other readers: I'm not coding this for the OP, because he will learn more by coding it himself.)
You can create a matrix using 2 dimensional arrays:
int[][] matrix = new int[row][column]; //row is the number of matrix rows
//column is the number of matrix columns
To access the elements of the matrix and define it after the declaration, you can use a nested for loop:
for (i = 0; i < row; i++ )
for (j = 0; j < column; j++)
{
scores[i][j] = value; // value is your chosen integer for that index
}
}
As you mention in your question, user has to input only onces and that it places in all four slots.
For example, if user input is 1 then the matrix looks like this 1 1 1 1.
Then no need for first for loop, just remove it.
int number;
System.out.println("What are the dimensions of the matrix?");
number = in.nextInt();
System.out.println("What are the numbers in your matrix?");
int matrix_number = in.nextInt();
for (int i = 0; i < number; i = i + 1)
{
for (int j = 0; j < number; j = j + 1)
{
System.out.print(matrix_number);
}
System.out.println();
}
You want the user to say the size of the square matrix, then you want the user to tell you every number in the matrix. You only need two loops here:
int number;
System.out.println("What are the dimensions of the matrix?");
number = in.nextInt();
for (int i = 0; i < number; i = i + 1)
{
for (int j = 0; j < number; j = j + 1)
{
System.out.println("What are the numbers in your matrix?");
int matrix_number = in.nextInt();
System.out.print(matrix_number);
}
System.out.println();
}
If you don't want your matrix polluted by "What are the numbers in your matrix?" questions, then you're going to need to learn how to store user input into some sort of data structure. As you said in your question, arrays are a great way to do this (as are 2d arrays).
If you were willing to learn file input or file output, then you could do what you seek without "storing" the numbers in an array. Either read the numbers in from a file and output them to the screen, or have the user type them as user input and output the matrix to a file.
Edit: You could try to erase the "What are the numbers in your matrix?" system out by printing backspace characters on linux systems. More here:
How to delete stuff printed to console by System.out.println()?
Sorry,this is a homework problem. I am not good with maths, so I checked out some videos to understand how two matrices are multiplied. I came up with a formula, but I do not know what I am doing wrong? This question has been answered before, but I did not understand. Thank you.
case 3:
System.out.println("THE PRODUCT OF TWO MATRICES ARE: ");
for(i =0; i< arrayList.length; i++){
for(j =0; j< arrayList1.length; j++){
for(k =0; k < arrayList1.length;k++){
multiplication = arrayList[i][k] * arrayList1[k][j] + multiplication;
}
System.out.print(arrayList[i][j]+" ");
}
System.out.println();
}
break;
First of all you should understand that the multiplication of two matrices should result in a matrice (which not appear to be the case with your multiplication variable).
I suppose you have to program the basic implementation. Let's take a look at the following matrices.
A has n rows, and m columns; said to be a matrice n x m.
Similary, B has m rows and p columns (m x p matrice). The multiplication of A x B will give you a matrice n x p.
Note that if you want to do the multiplication A x B, the matrice A must have the same number of columns that the number of rows of the matrice B.
Now each value in the matrice AB (ith row and jth column) is computed as follow:
That said, let's take a look at the Java implementation (which is a pure translation of the mathematical formula).
public static int[][] multiply(int[][] matrixA, int[][] matrixB) {
int[][] result = new int[matrixA.length][matrixB[0].length];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++) {
for (int k = 0; k < matrixB.length; k++) {
result[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}
return result;
}
The result matrice is initialized at the right dimensions. Then the first two nested loop (with indices i and j) will loop through all the elements of elements of the resulting matrice. Then you just need the third loop to compute the sum.
You'd still need to check that the matrices you give as parameters have the correct length.
The algorithm used is pretty naive (O(n3) complexity). If you don't understand it, there's a lot of resources in the web that explains how it works; but that would more a mathematical question than a programming one.
Hope it helps ! :)
How do I search a 2D array for a specific number (1)? I thought the following code did it, but apparently I was looking in a specific spot whenI declared it with [4][4].
boolean undirectedCircuit (int [][] graph)
{
//graph = graph1(graph1(null));
int edgeCounter = 0;
for (int edge = 0; edge < graph.length; edge++)
{
/* SET FOR WHEN 1s are found in array: edgeCounter++;*/
if(graph[4][4] == '1')
{
edgeCounter++;
System.out.println("edgeCounter found '1' " + edgeCounter + "times");
}
}
if (edgeCounter % 2 == 0)
{
System.out.println("This is a circuit!");
//return true;
}
else System.out.println("This is not a circuit!!");
return false;
}
public void go ()
{
graph1 = new int[][] //This line is complained about.
{
{0,1,1,1,0},
{1,0,0,0,1},
{1,0,0,1,0},
{1,0,1,0,1},
{0,1,0,1,0}
};
undirectedCircuit(graph1); //This is complained about.
}
This is part of an assignment from my school, just pointers would be great. Thank you!
This line is wrong in two ways:
if(graph[4][4] == '1')
The quotes around '1' make it a char literal. Since your array contains ints, you'll want to drop the quotes and just write 1.
graph[4][4] will always check the same value in the array as you said. Specifically, it will always access the fifth value in the fifth array of your 2d array. Whenever you write numbers in your code, they are constants: the number 4 is never going to change during your program's execution, so you keep using 4 as the index over and over again, accessing the fifth element each time you do so.
In order to access every element in an array, you can loop over it like this:
for (int n = 0; n < array.length; n ++)
{
array[n]; //access the nth element of the array
}
n in this instance is the same as your edge variable.
However, since you are using a 2d array, these elements are themselves arrays! Therefore, you need another loop:
//array is a 2d array...
for (int n = 0; n < array.length; n ++)
{
//...so its elements are 1d arrays
for (int m = 0; m < array[n].length; m ++)
{
array[m][n]; //here we have a specific object in our 2d array.
}
}
We use variables for our indices so they can change in the loop and access different values in the array. Hope this helps!
You could try something like this where you will iterate through both dimensions of the array and check your current location rather than the 4,4
for (int x = 0; x < graph.length; x++)
{
for (int y = 0; y < graph[x].length; y++)
{
/* SET FOR WHEN 1s are found in array: edgeCounter++;*/
if (graph[x][y] == 1)
{
edgeCounter++;
System.out.println("edgeCounter found '1' " + edgeCounter + "times");
}
}
}