I am fairly new at Java and have been having some issues understanding a code within my course and it is slowing me up. Can someone kindly give me a step by step of what the 1st for loop is doing? I get confused at what value is arr[row] getting?
When I look at the result it makes sense that it is 1 2 3 4 5 6 BUT is the 1st for loop generating and then going to the second one? if so, what is the second one doing since we are starting at row=0? and col=0? I really need help to move forward with this. Here is the code:
public static void main(String[] args) {
int[][] arr = new int[6][];
for(int row = 0; row < arr.length; row++)
arr[row]= new int[row + 1];
for(int row = 0; row < arr.length; row++){
for(int col = 0; col < arr[row].length; col++){
arr[row][col] = (row + 1) *(col +1);
//System.out.print(arr[row][col] + " ");
System.out.print("row[" + row + "]"+ "col["+col +"]= "+arr[row][col] + " ");
}
System.out.println(); //new line
}
}
It is just creating a multidimensional array, each row with one more slot then the previous.
Something like this:
[]
[][]
[][][]
[][][][]
[][][][][]
[][][][][][]
The second (couple of) for scans every element and assign a value proportionated to its dimensions. So it'll be:
[1]
[2][4]
[3][6][9]
[4][8][12][16]
[5][10][15][20][25]
[6][12][18][24][30][36]
It really reminds me of Fibonacci sequence
Hope I helped
Related
I am doing an assignment for class and I cant figure out what I need to change and exactly where. I am starting to understand better how it all works together. However, I have tried quite a few variations that I thought might work, but they never turn out how I had intended.
The first 5 pieces of code I have gotten to work correctly through trail and error, but that 6th code/problem I can't quite figure out.
My initial code to create the 2D array is this:
public static void main(String[] args) {
int[][] numbers = {{1,1,1,1,1},{2,2,2,2,2},{3,3,3,3,3},{4,4,4,4,4},{5,5,5,5,5}};
//made this to go around Scanner to save time/workload
for(int rows = 0; rows < 5; rows++) {
for(int columns = 0; columns < 5; columns++) {
}
}
And the code that I am having trouble with is:
System.out.println("2) Your entered values are now : ");
System.out.println( );
for(int rows = 0; rows < 5; rows++) {
for(int columns = 0; columns < rows + 1; columns++) {
System.out.print(numbers [rows][columns]);
} // will replace w/ System.out.print("*"); to get asterisks instead of numbers
System.out.println( );
}
/*needs to Output ***** Outputs 1
**** 22
*** 333
** 4444
* 55555 */
I have separated all 6 problems within the code and they all run off of the same input (int numbers[5][5]) and utilized similiar code. They all are displayed on a single page after each other.
The problem on the way you are using for loops to print your 2d array
you are doing it in the wrong way
you can fix it by changing this condition columns < rows + 1 to columns < 5 - rows at inner loop:
for(int rows = 0; rows < 5; rows++) {
for(int columns = 0; columns < 5 - rows; columns++) {
System.out.print(numbers [rows][columns]);
} // will replace w/ System.out.print("*"); to get asterisks instead of numbers
System.out.println( );
}
You need your rows to count from 4 to 0 instead of 0 to 4. Feel free to comment here and I'll provide additional assistance if needed.
#Maybe_Factor
Figuring that part was easy. We had figured out what the problem was a hour after the original posting.
Here is the new code:
System.out.println("6) Your entered numbers are now : ");
System.out.println( );
for(int rows = 0; rows < 5; rows++) {
for(int columns = 0; columns < 5- rows ; columns++) {
System.out.print("*");
I have searched far and wide for information on this subject to no avail. I am really struggling with Java Loops.
I get the big picture ideas of For/While loops, but when it comes time to actually start programming, I get error after error...
I have tried writing out my program and understanding the logic of it, but I cannot seem to get the program to do what I want it to do.
The task at hand:
Write a program using a Scanner that asks the user for a number n between 1 and 9 (inclusive). The program prints a triangle with n rows. The first row contains only the square of 1, and it is right-justified. The second row contains the square of 2 followed by the square of 1, and is right justified. Subsequent rows include the squares of 3, 2, and 1, and then 4, 3, 2 and 1, and so forth until n rows are printed.
Assuming the user enters 4, the program prints the following triangle to the console
1
4 1
9 4 1
16 9 4 1
For full credit, each column should be 3 characters wide and the values should be right justified.
So far, I have come close (not including the user input for now, just trying to at least get a grasp on the looping aspect and then I will work on that):
public class MyClass {
public static void main(String args[]) {
int rows = 4; // this is the value that the user will enter for # of rows
for (int i = 1; i <= rows; i++) {
for (int j = i; j >= 1; j--) {
System.out.print((j*j)+" ");
}
System.out.println();
}
}
}
PRINTS:
1
4 1
9 4 1
16 9 4 1
You have two problems.
First, you need the numbers printed with padding on the left to produce the number in the space of 3 characters. Look at System.out.printf("%3d", ...)
Second, you need to print out additional blank columns. 3 blank columns on the first row, two blank columns on the second row, 1 blank column on the third row, and zero blank columns on the last row. Sounds like another inner loop.
int rows = 4; // this is the value that the user will enter for # of rows
for (int i = rows; i > 0; i--) {
for (int j = rows; j > 0; j--)
System.out.print((rows - j + 1) < i ? " " : String.format("%3d", j * j));
System.out.println();
}
You actually need to print a square table, not a triangle. It's just that some of the cells in the table will be filled with spaces.
This means that your algorithm should be something like this:
for row from 1 to n
for col from n to 1 /* Note: It's not from row to 1 */
if col <= row print square(col)
else print pad
import java.util.Scanner;
public class TriangleOfSquares {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer between 1 and 9: ");
int n = input.nextInt();
for (int i = n; i > 0; i--) {
for (int j = n; j > 0; j--)
System.out.print((n - j + 1) < i ? " " : String.format("%3d", j * j));
System.out.println();
}
}
}
Ok, so I got this program that prints out a pyramid!
Heres the code:
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.print("How many rows?: ");
int amountOfRows = keyboard.nextInt();
int maxIndentation = amountOfRows + 2;
for(int row = 0; row < amountOfRows; row++){
int antallx = 2*row;
// indent
for(int column = 0; column < maxIndentation - antallx / 2; column++){
System.out.print(" ");
}
// prints a row
System.out.print("d");
for(int kolonne = 0; kolonne < antallx; kolonne++){
System.out.print("0");
}
System.out.println("b");
}
}
Question: I know a bit about how for-loops etc work, but what I am wondering is if someone could please explain what the for-loops does in this program and also a bit about the choose of the variables, specially when it comes to adding and or multiplying them with a number (that part is confusing me a lot, how they decide if they want to +2 the variables like with amountOfRow, and multiply with 2 like for antallx)?, and im also wondering big time on the second for loop, how do they come up with dividing by 2 etc? any help would be much appreciated! thanks in advance! :)
I took a look at that application, and it is doing it in a way in order to teach you about both loops and mathematics. Specifically look at your example and focus on the following lines
column < maxIndentation - antallx / 2
What is maxIndentation - antallx / 2 equal to? Recall antallx = 2 * row
Then I would test your pyramid program with different inputs (1, 2, 3, ...) to see how each of them changes the final output of the program.
Here is a commented version of your program that I hope shows you how this program works. You can also use an online IDE to see the code compiled, see here
// This program will output the following type of pyramid
// db
// d00b
public static void main(String[] args){
//a scanner is a tool for reading input from a stream
//in this case, you are reading from the user input window (console)
//Scanner keyboard = new Scanner(System.in);
//asks users how many rows of a pyramid they want
System.out.print("How many rows?: ");
//int amountOfRows = keyboard.nextInt();
for(int i = 0; i < 5; i++)
{
printPyramid(i);
System.out.println("\n\n"); //this line essentially prints a newline x3
}
}
public static void printPyramid(int amountOfRows)
{
int maxIndentation = amountOfRows + 2;
for(int row = 0; row < amountOfRows; row++){
int antallx = 2*row;
for(int column = 0; column < maxIndentation - antallx / 2; column++){
System.out.print("|");
//I changed " " to "|" so you can see what this for loop is printing
}
System.out.print("d");
for(int kolonne = 0; kolonne < antallx; kolonne++){
System.out.print("0");
}
System.out.println("b");
}
}
Its all about logic.
1) Just like what you said, It prints a pyramid
2) maxIndention and antallx variables are just used for spacing. The programmer just only wants that logic to be applied into his program. You can do another different logic if you wanted.
Okay, so you have 2 for loop one inside the other.
The first loop: Row =0; is the starting point, so your loop with start at zero.
Then it check for your condition, and if it is true row it will run thr codr below the forloop and will iincremented by 1 so the next row is now 1. It will do this as long as your , condition is true.
The second loop: will do the same thing however when row = 0; column will start at zero and execute until the condiction becomes false, when row =1 the condiction column will again start at zero and execute until the condiction is false. It will do this until the first loop becomes false.
Really life example
You have 20 dollar and you used 10 dollar for a burger, after couple hour you feel hungry again and you buy other burger the same price. You only do that as long as you have more than 10 dollars. If you have less thecondition becomes false.
I have two java 2D arrays(array1 and array2), both of type Double which I would like to join together.
array1 and array2 are n-by-d matrices. the n-rows for each array can vary from eachother but the d-columns are always the same.
The question is: i have to concatenate array2 after the first one.(at best into the new outputMatrix)
Example:
array1:
2 3
6 5
4 7
array2:
1 5
3 7
Output Array (n-array1 + n-array2)-by-d:
2 3
6 5
4 7
1 5
3 7
My idea was to copy array1 into the outputMatrix, and then fill the continuation of it with array2.
My Java code for merging the two arrays(that are already implemented) looks like:
private static double[][] outputMatrix ;
outputMatrix = new double[array1.length+array2.length][array1[0].length];
for (int column = 0; column < array1[0].length; column++) {
for (int row = 0; row < (array1.length); row++) {
outputMatrix[row][column] = array1[row][column];
}
}
for (int column = 0; column < array1[0].length; column++) {
for (int row = array1.length; row < (array1.length+ array2.length); row++) {
outputMatrix[row][column] = array2[row][column]; //error here as array2 starts iterating at field [4][0] which isnt defined in the example
}
}
Your indices are wrong.
Should be
for (int column = 0; column < array1[0].length; column++) {
for (int row = 0; row < array2.length; row++) {
outputMatrix[row+array1.length][column] = array2[row][column];
}
}
since array2 has indices from 0 to array2.length-1.
So what's happening is that when you are trying to transfer the data from the second array into the outputMatric variable, you go out of bounds in the second array (array2). This is due to the fact that you're outputMatrix is trying to put a value at [array1.length + row][array1.length + column] and the second array isn't as big as that one. On top of that, your row index is wrong, you need to add the array1 length to make up for it or start the for loop's row variable at that spot. I elected just to add the length into the storing of the variable. So, you should make your code:
outputMatrix[row + array1.length][column] = array2[row - array1.length][column - array1[0].length];
I have made a program that outputs the number of repeats in a 2D array. The problem is that it outputs the same number twice.
For example: I input the numbers in the 2D array through Scanner: 10 10 9 28 29 9 1 28.
The output I get is:
Number 10 repeats 2 times.
Number 10 repeats 2 times.
Number 9 repeats 2 times.
Number 28 repeats 2 times.
Number 29 repeats 1 times.
Number 9 repeats 2 times.
Number 1 repeats 1 times.
Number 28 repeats 2 times.
I want it so it skips the number if it has already found the number of repeats for it. The output should be:
Number 10 repeats 2 times.
Number 9 repeats 2 times.
Number 28 repeats 2 times.
Number 29 repeats 1 times.
Number 1 repeats 1 times.
Here is my code:
import java.util.Scanner;
public class Repeat
{
static Scanner leopard = new Scanner(System.in);
public static void main(String [] args)
{
final int ROW = 10; //Row size
final int COL = 10; //Column size
int [][] num = new int[ROW][COL];
int size;
//Get input
size = getData(num);
//Find repeat
findRepeats(num, size);
}
public static int getData(int [][] num)
{
int input = 0, actualSize = 0; //Hold input and actualSize of array
System.out.print("Enter positive integers (-999 to stop): ");
//Ask for input
for(int i = 0; i < num.length && input != -999; i++)
{
for(int j = 0; j < num[i].length && input != -999; j++)
{
input = leopard.nextInt();
//Check if end
if(input != -999)
{
num[i][j] = input;
actualSize++;
}
}
}
System.out.println();
return actualSize;
}
public static void findRepeats(int [][] num, int size)
{
int findNum;
int total = 0, row = 0, col = 0;
for(int x = 0; x < size; x++)
{
//Set to number
findNum = num[row][col];
//Loop through whole array to find repeats
for(int i = 0; i < num.length; i++)
{
for(int j = 0; j < num[i].length; j++)
{
if(num[i][j] == findNum)
total++;
}
}
//Cycle array to set next number
if(col < num[0].length-1)
col++;
else
{
row++; //Go to next row if no more columns
col = 0; //Reset column number
}
//Display total repeats
System.out.println("Number " + findNum + " appears " + total + " times.");
total = 0;
}
}
}
I know why it is doing it, but I cannot figure out how to check if the number has already been checked for it to skip that number and go to the next number. I cannot use any classes or code that is not used in the code.
Since you cannot use anything other than this, lets say, basic elements of Java consider this:
Make another temporary 2D array with two columns (or just two separate arrays, personally I prefer this one). On the start of the algorithm the new arrays are empty.
When you take a number (any number) from the source 2D structure, first check if it is present in the first temporary array. If it is, just increment the value (count) in the second temporary array for one (+1). If it is not present in the first tmp array, add it to it and increase the count (+1) in the second at the same index as the newly added number in the first (which should be the last item of the array, basically).
This way you are building pairs of numbers in two arrays. The first array holds all your distinct values found in the 2D array, and the second one the number of appearances of the respective number from the first.
At the and of the algorithm just iterate the both arrays in parallel and you should have your school task finished. I could (and anyone) code this out but we are not really doing you a favor since this is a very typical school assignment.
It's counting the number two times, first time it appears in the code and second time when it appears in the code.
To avoid that keep a system to check if you have already checked for that number. I see you use check int array but you haven't used it anywhere in the code.
Do this,
Put the number in the check list if you have already found the count of it.
int count = 0;
check[count] = findNum;
count++;
Note: You can prefill you array with negative numbers at first in order to avoid for having numbers that user already gave you in input.
Next time in your for loop skip checking that number which you have already found a count for
for(int x = 0; x < size; x++) {
findNum = num[row][col];
if(check.containsNumber(findNUm)) { //sorry there is no such thing as contains for array, write another function here which checks if a number exists in the array
//skip the your code till the end of the first for loop, or in other words then don't run the code inside the for loop at all.
}
}
Frankly speaking I think you have just started to learn coding. Good luck! with that but this code can be improved a lot better. A piece of advice never create a situation where you have to use 3 nested for loops.
I hope that you understood my solution and you know how to do it.
All answers gives you some insight about the problem. I try to stick to your code, and add a little trick of swap. With this code you don't need to check if the number is already outputted or not. I appreciate your comments, structured approach of coding, and ask a question as clear as possible.
public static void findRepeats(int [][] num, int size)
{
int findNum;
int total = 1, row = 0, col = 0;
int [] check = new int[size];
while(row < num.length && col < num[0].length)
{
//Set to number
findNum = num[row][col];
//Cycle array to set next number
if(col < num[0].length-1)
col++;
else
{
row++; //Go to next row if no more columns
col = 0; //Reset column number
}
//Loop through whole array to find repeats
for(int i = row; i < num.length; i++)
{
for(int j = col; j < num[i].length; j++)
{
if(num[i][j] == findNum) {
total++;
//Cycle array to set next number
if(col < num[0].length-1)
col++;
else
{
row++; //Go to next row if no more columns
col = 0; //Reset column number
}
if(row < num.length - 1 && col < num[0].length -1)
num[i][j] = num[row][col];
}
}
}
//Display total repeats
System.out.println("Number " + findNum + " appears " + total + " times.");
total = 1;
}
}
you can use a HashMap to store the result. It Goes like this:
// Create a hash map
HashMap arrayRepeat = new HashMap();
// Put elements to the map
arrayRepeat.put(Number, Repeated);