(Java beginner)
I came up with a code that would display an int array in reverse and although I know there's probably a better way to do it, I think this logic should work:
for(int i = 0, j = numList.length - 1; i < j; i++, j--)
{
int temp = numList[i];
numList[i] = numList[j];
numList[j] = temp;
System.out.print("Reverse order: " + temp + " ");
}
What I don't understand is that when I enter 5 numbers, the console only shows the first two numbers and it ends there:
1
2
3
4
5
Reverse order: 1 2
What's wrong here and what can I do to fix it?
That code is just faulty. Use this instead.
for(int i = numList.Length - 1; i >= 0;i--)
{
int temp = numList[i];
System.out.print("Reverse order: " + temp + " ");
}
In your code, you increment i and decrement j, meaning that if you'd loop untill your condition is satisfied, you'd get about half the loop done. Try and create a table of the values of your loop step by step, you'll see what I mean :)
i++ and j-- along with the loop iteration condition of i < j would become false when i and j reach the middle of the array. So essentially your for loop is only working up the first half of the loop. I didnt run you code but this is the first observation i made.
Related
Could someone explain the basics behind printing simple patterns in Java?
I'll give one specific example.
I'd just like for someone to clarify what each line is doing so I get a better understanding of how this works. Any other explained examples (line by line) would also be appreciated!
public static void drawPyramidPattern() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5 - i; j++) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}
}
Printing anything or everything via a loop is just about understanding the flow of execution. In your code also, if you'll start watching the flow line by line you'll come to know that how it is working exactly.
If you understand how it works, you would be able to print any pattern, but basics should be clear. Try printing variable i, j and k values after each iteration. See the values that how that gets changed after each cycle of execution and then see the logic you've applied.
Your question is somewhat very broad in scope and can not be answered exactly unless narrowed it down. I would suggest to run this line by line and watch the output, try more changes even if it doesn't make any sense, you'll be having a good understanding over looping even for all of your future tasks. And if after trying yourself, you come to any problem, share here, people are ready to solve them. :)
Hope this helps.
First you must a have complete understanding of loops, nested loops then you come up to patterns designing.
1) First run the loops in hard form like on Register/on Page for understanding the loops.
2) Use debugger to identify the loop progress.
If you think about it in terms of mathematics, loops are just functions.
A single for loop would just be x.
Example
for (int i = 0; i < 5; i++) {
System.out.println("This is function x.");
}
However when you start nesting loops it because a greater function. A for loop inside another for loop would be a function x^2
For example:
for (int i = 0; i < 5; i++) {
for (int j = 0; J < 5; j++){
System.out.println("This is the j loop");
}
System.out.println("This is the i loop");
}
The reason behind this is because in order to finish the first iteration of i, everything inside the loop must be completed. But, the i loop has another loop inside of it, so that must be finished first. So the loop with j must execute until it is finished. (In this case 5 times), Great, now we can increment i. But now we have to step through j again! This process continues until i reaches its threshold of being < 5. So the output would look something like this
Output:
This is the j loop
This is the j loop
This is the j loop
This is the j loop
This is the j loop
This is the i loop
This is the j loop
This is the j loop
....
This would continue until the i has reached 5, in which case it no longer satisfies the necessary i < 5, and the loop would end. Hopefully this helps
First, since i = 0 & 0<5 is true you enter the first(outer) for-loop.
Remember i = 0.
Then j = 0; but 0 < i = 0 is false so you don't enter the second loop.
For the third loop, k = 0 & 0<=0 is true. So you enter the loop and execute the print statement, i.e print a star.
k++, this will increment k by 1 and check the boolean; You ask yourself is 1 <= 0; clearly no ; so you exit the for-loop and then reach the println statement which will take you to the next line.
And then you go back to the outer loop.
//this code print Diagonal Pattern if matrix is
1 2 3
4 5 6
7 8 9
output is :
1
4 2
7 5 3
8 6
9
import java.util.*;
class DiagonalPattern
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int x[][];
int i,j,row,col,p,temp=1,last=0;
System.out.println("how many array wants to create and size of array");
row=sc.nextInt();
col=sc.nextInt();
x=new int[row][col];
System.out.println("Enter " +row*col+ " elements of array of array");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
x[i][j]=sc.nextInt();
last=j;
}
}
for(i=0;i<row;i++)
{
System.out.println("");
int k=i;
for(j=0;j<=i;j++,k--)
{
if(j==col)
{
break;
}
else
{
System.out.print(x[k][j]);
System.out.print(" ");
}
}
}
for(p=x.length;p>0;p--,temp++)
{
System.out.println("");
i=x.length-1;
int k=i;
for(j=temp;j<=last;j++,k--)
{
System.out.print(x[k][j]);
System.out.print(" ");
}
}
}
}
I am working on an assignment where I need to create two arrays, then look through them and create a new array that holds any values inside of both the first two. Originally, I was close to accomplishing this by making an arraylist but my lab professor told me that wasn't allowed so I needed to re-start and didn't have enough time to figure out the solution.
If you'd like to see the whole code I have now: http://pastebin.com/thsYnj2z
I am really struggling with this loop here:
for(int i = 0 ; i < Xarr.length ; i++){
for(int j = 0 ; j < Yarr.length ; j++)
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
k++;
System.out.println(ArrA[k]);
break;
}
My output is remaining 0 for my ArrA[k] array. I can't seem to trouble shoot this issue on my own.
try making these changes
for(int i = 0 ; i < Xarr.length ; i++){
for(int j = 0 ; j < Yarr.length ; j++)
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
System.out.println(ArrA[k]); // or print them all later
k++;
break; // break to outer loop
}
}
}
note
Assuming OP has correctly initialized ArrA
note2
Assuming that only unique values are required, hence the breaking
Does your solution require that no values are duplicated in ArrA? Or are duplicate values allowed? For example, if some values occur multiple times in each array, you could get multiple matches on the same number.
If duplicates aren't a problem:
for(int i = 0 ; i < Xarr.length ; i++){
for(int j = 0 ; j < Yarr.length ; j++){
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
System.out.println(ArrA[k]);
k++;
}
}}
As I understand it, the problem is to take 2 arrays, and produce a third array which is a Union of the first 2. Union of 2 sets being the subset of the values found in both sets.
Your code was missing some braces, so put those back in there. Also you wont want to print the k+1th item after you just put a value in ArrA[k] im assuming.
Otherwise you were pretty much there. The break terminates the inner loop and allows the outer loop to increment i and continue on. This is because you have already found a match, no need to continue searching, just move onto the next index in Xarr.
Algorithm goes like this: For each value in X, search Y for a match. If it is found, add this value to A.
for(int i = 0 ; i < Xarr.length ; i++) {
for(int j = 0 ; j < Yarr.length ; j++) {
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
System.out.println(ArrA[k]);
k++; //you probably want to increment k after you add to ArrA, not before
break;
}
}
}
public static void main(String... args){
int[] xArr = {1, 1,1,1,1,1};
int[] yArr = {1, };
int[] kArr = new int[xArr.length > yArr.length ? xArr.length : yArr.length];
int k = 0;
for(int x = 0; x < xArr.length; x++){
for(int y = 0; y < yArr.length; y ++){
int xNum = xArr[x];
int yNum = yArr[y];
if(xNum == yNum) kArr[k++] = xNum;
}
}
int[] resizedKArr = new int[k];
for(int i = 0; i < resizedKArr.length; i++) resizedKArr[i] = kArr[i];
Arrays.sort(resizedKArr);
for(int x : resizedKArr) System.out.println(x);
}
First, xArr and yArr are given some random numbers, and then kArr is initialized with the size of the lagest array we are comparing with to ensure the array has enough space to hold similar values.
Then, in the next section we do a loop inside of a loop to compare the values against each other and if they are similar then k++ and set the next value in the array. This goes on until the loops are completed, notice there really is never a need to break from either loop until all values are compared. At that point the loops break themselves and move on to the next bit of code.
The last section is just to create an array of the same size as k and move the values over, I don't know the requirements of your studies, although when using primitives like this you may want to do this in case you have a matching 0 as a number. Otherwise you'll have a ton of 0s filling the empty spaces of your array.
And lastly, we just sort the array for good measure and print it out.
Hope I've answered your question and you get something out of this post!
The problem is printing ArrA[k] after k++. Try increasing line after print.
I'm trying to make a Java program that uses the input value from a user to calculate and list the products of two numbers up to the entered number. Like if a user enters 2, the program should calculate the products between the two numbers (1 *1, 1*2, 2*1, 2*2) stores the products in a two-dimensional array, and list the products. I'm not sure that I totally understand arrays and so I feel as though my code is problem not right in many instances, can someone please tell me what I should do to my current code to make it work properly. Thanks in advance! :)
import java.util.Scanner;
public class ProductTable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inputString;
char letter = 'y';
// Prompt the user to enter an integer
while(letter != 'q') {
System.out.print("Enter a positive integer: ");
int integer = input.nextInt();
// Create an two-dimensional array to store products
int[][] m = new int[integer][3];
for (int j = 1; j <= m.length; j++) {
m[j][0] = input.nextInt();
m[j][1] = input.nextInt();
m[j][2] = input.nextInt();
}
// Display the number title
System.out.print(" ");
for (int j = 1; j <= m.length; j++)
System.out.print(" " + j);
System.out.println("\n--- ");
// Display table body
for (int i = 1; i <= m.length + 1; i++) {
System.out.print(i);
for (int j = 1; j <= m.length + 1; i++) {
System.out.printf("%4d", i * j);
}
System.out.println();
}
// Prompt the user to either continue or quit
System.out.print("Enter q to quit or any other key to continue: ");
String character = input.nextLine();
inputString = input.nextLine();
letter = inputString.charAt(0);
}
}
}
You can achieve your multiplication table by iterating over 2 counter variables as you already did in your output
// Display table body
// loops running out of bounds (until m.length + 1 instead of m.length-1)
for (int i = 1; i <= m.length + 1; i++) {
System.out.print(i);
for (int j = 1; j <= m.length + 1; i++) { // missed to increment j here
System.out.printf("%4d", i * j);
}
System.out.println();
}
Arrays should be based on 0, that means an array with 3 fields has the indexes 0, 1, 2. So the last index is length-1. Your condition <=m.length+1 runs out of bounds. index<length will work since 2 is less than 3, but not 3 less than 3.
You have also a typo: In the inner loop you are doing an increment of i instead of j, so the loop will run infinite.
Try to create an outer and inner loop as you did, but with start index 0 and end condition index<inputValue. Calculate multiTable[index1][index2] = (1+index1)*(1+index2).
Then do a similar loop and print the array fields. You don't need to use an array, you could output directly as you did. But you wanted to practice handling arrays.
Since you want to learn and understand, I don't like just to write the code. imagine an array with 3 fields having the indexes 0, 1, 2:
index 0 | 1 | 2
value 1 | 2 | 3
Now you would check the length at first, that's 3. You start with 0 and count while the counter does not reach the length since the zero based index is 1 below our natural order (0,1,2 vs. 1,2,3). That is the case as long the index is below the length, meaning index<length.
Try this logic (pseudo code). To simplify the problem we include the 0 in our product table. So we get 0*0, 0*1, 0*2... Doing so, we do not have to ignore index 0 or to calculate between index 0 should represent value 1.
maxNumber = userInput()
outer loop idx1 from 0 to maxNumber
inner loop idx2 from 0 to maxNumber
array[idx1][idx2] = (idx1) * (idx2)
end loop
end loop
Do the same to dump your generated array to screen.
First get it running. Afterwards you could try to alter the logic, so that it shows you only numbers from 1 to max.
I am trying to print the picture below using nested loops (I should use for & while loops):
**
****
******
********
Starts with 5 spaces, decreasing by 2 each line.
Starts with 2 stars, increasing by 2 each line.
Ends at 4 lines.
My code works on the first line, but it does not print the stars on the remaining 3 lines. Can someone see what the error may be? Please do not give the answer, I just need help understanding the logical error!
int m = 6;
int n = 0;
for(int l = 1; l < 5; l++){
while(m > 0){
System.out.print(" ");
m--;
}
while(n < (2*l)){
System.out.print("*");
n++;
}
System.out.println();
m = 5 - (2*l);
n = n + 2;
}
The error is that you don't reset the n variable each loop. You add 2 to it after the first loop at which point is is already larger than 2 * l so no more stars will be printed.
It would be more sensible to structure it as:
for (int l = 0; l < 4; l ++) {
for (int i = 0; i < 5 - 2l; i++)
System.out.print(" ");
for (int i = 0; i < 2 + 2l; i++)
System.out.print("*");
System.out.println();
}
Hint:
look at m=5 - (2×l);
as soon as l=3
the result will be negativ and the first while-loop wont be executed
Just like you add two to n, you have to remove 2 from m. If I understand quite well, m is your number of spaces and n is your number of stars so if you add two stars; n+2 then you have to remove the space too so: m - 2 since the two added stars occupy that space.
m = m - 2;
n = n + 2;
Edit: you also have to change the while loop where the n is edited, in order not to change the n:
int temp = n;
while(temp > (2*l)){
System.out.print("*");
temp++;
}
Use nested for loops the outer loop moves down the rows and the inner loop moves along the columns. Each pass through the inner loop should check whether ro place an empty space or an asterisk. This can be done with an if statement use the integer variables in the for loops to determine when to place a space or an asterisk. The algorithm for this will vary depending on the shape you want.
Alternatively the use of a doubly indexed array might be interesting here. More complext but maybe something to look at if you need to use a while loop. It might be possible to use for loops to fill a doubly indexed char array with either a " " or a "*" and then simply print out ghe contents of the array while setting the value to null after printing and checking to see if the array is empty or not.
Maybe some of this was helpful. Happy coding.
Problem
I have written a loop in which I fill an array with Sum objects. Everything works fine, but as soon as the loop gets to the next iteration it overwrites the first index of the array.
What have I tried
I tried to see if maybe my problem resides in a different piece of code (such as my Sum class). But could not find anything that would disturb the loop.
I tried to find other variables with the same name (even in other methods, since I was desperate) and see if I maybe changed my iterator somewhere else. I couldn't find anything related to that.
I tried looking around on the internet and SO to find something related to accidentally overwriting arrays but couldn't find anything either.
Code
public Task(Object[] parameters)
{
this.number_of_sums = Integer.parseInt((String)parameters[0]);
this.variables_per_sum = Integer.parseInt((String)parameters[1]);
this.sum_parameters = new Object[this.variables_per_sum];
this.sums = new Sum[this.number_of_sums];
int z = 0;
for(int i = 0; i < this.number_of_sums; i++)
{
int x = 0;
for(int j = (2 + z); j < ((this.variables_per_sum + 2) + z); j++)
{
this.sum_parameters[x] = parameters[j];
x++;
}
this.sums[i] = new Sum(this.sum_parameters);
System.out.println("Index 0: "+sums[0]); //1st iteration: 1 + 1 //2nd iteration: 2 - 1
System.out.println("Index 1: "+sums[1]); //1st iteration: null //2nd iteration: 2 - 1
z += this.variables_per_sum;
}
}
Expectations
I'm expecting the output of 1 + 1 and 2 - 1. I am however getting the following: 2 - 1 and 2 - 1 when I'm done.
If anyone spots anything I'm doing wrong or would like to see more information or code on my side please say so. Thanks in advance.
I'm going to assume the Sum class doesn't store its sum, but instead computes it from the array it was constructed with whenever it's needed.
It looks like all the Sum objects will share the same array -- you're passing the same reference every time you construct a Sum. Furthermore, every time you loop over j you overwrite the contents of that array.
So when everything is done, all the sums are the same.
You should be able to get around this by giving each Sum a different sum_parameters:
public Task(Object[] parameters)
{
this.number_of_sums = Integer.parseInt((String)parameters[0]);
this.variables_per_sum = Integer.parseInt((String)parameters[1]);
this.sums = new Sum[this.number_of_sums];
int z = 0;
for(int i = 0; i < this.number_of_sums; i++)
{
Object[] sum_parameters = new Object[this.variables_per_sum];
int x = 0;
for(int j = (2 + z); j < ((this.variables_per_sum + 2) + z); j++)
{
sum_parameters[x] = parameters[j];
x++;
}
this.sums[i] = new Sum(sum_parameters);
System.out.println("Index 0: "+sums[0]); //1st iteration: 1 + 1 //2nd iteration: 2 - 1
System.out.println("Index 1: "+sums[1]); //1st iteration: null //2nd iteration: 2 - 1
z += this.variables_per_sum;
}
}
Each one of your Sum objects is constructed with this.sum_parameters as a parameter:
this.sums[i] = new Sum(this.sum_parameters);
When sum_parameters is modified in each iteration of the outer loop, it changes internally in the objects constructed around references to it.
You should make an internal copy of sum_parameters in each Sum object.