Issue
I am new to Java and just start my journey but i have problem with this simple function. I am should have result like that *2345 **345 ***45 ****5 But my function return something else :D What should I have to change?
public class Main08 {
public static void main(String[] args) {
int n = 5;
for (int i = 0; i < n; i++) {
String row = "";
for (int j = 0; j < n; j++) {
if (j < n) {
System.out.println(row += "*");}
else {
System.out.print(n);}
}
}
}
}
Solution
You can try like this:
public class MyClass {
public static void main(String[] args) {
int n = 5;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n; j++) {
if (j <= i) {
System.out.print("*");
} else {
System.out.print(j + 1);
}
}
System.out.print(" ");
}
}
}
Your issue is, that you prolonged the string multiple times and every time print it out again. I changed it such, that I only print out the numbers and asterisks depending on how the i and j relate to each other.
Also i limit the outer loop to n-1, because otherwise you will print 6 blocks (because you are starting from zero) and have a block of only asterisks at the end.
Output: *2345 **345 ***45 ****5
Answered By - Christian
Answer Checked By - Robin (JavaFixing Admin)