Before you reuse any variables, you must always therefore reset or reinitialize them. This means assign the variables the same values you assigned them at declaration, i.e. set integers to zero again, etc. However, do not declare the variables again. Reuse the existing variables, do not create new ones (typing in the data type means you are declaring a new variable).
CodePudding user response:
Write x = 0;
, or similar. It's difficult to see how you're getting very far without having met the assignment statement. Are you just confused about the distinction between assignment and declaration with initialization?
Declaration: int x;
Declaration with initialization: int x = 0;
Assignment: x = 0;
CodePudding user response:
You don't have any description of what you are trying to do, however, a Google search of your quoted text in the question suggests that you are trying to solve the *
triangle problem using loops:
*
**
***
So to reset and re-use your variables, you probably need something like this:
public static void main(String args[]) {
final int N = 5; // Number of rows to print the "stars"
int row = 0;
int col = 0; // This will be re-used every row to start printing "stars" and will have to be re-initialized
while (row < N) {
col = 0; // Re-initialize variable to re-use on new row
while(col <= row) {
System.out.print("*");
col ;
}
System.out.println();
row ;
}
}
Note: I'm not trying to provide an ideal solution to the triangle problem (I haven't seen the full problem description and this can be improved), but rather show how to re-initialize a variable in a loop. The col
variable here is declared outside of the loops and re-initialized in the outer loop for each iteration of the outer loop.