Write Java (Zybook 6.6.1) Print numbers 0, 1, 2, ..., userNum as shown, with eac
ID: 3577185 • Letter: W
Question
Write Java (Zybook 6.6.1)
Print numbers 0, 1, 2, ..., userNum as shown, with each number indented by that number of spaces. For each printed line, print the leading spaces, then the number, and then a newline. Hint: Use i and j as loop variables (initialize i and j explicitly). Note: Avoid any other spaces like spaces after the printed number. Ex: userNum = 3 prints:
public class NestedLoop {
public static void main (String [] args) {
int userNum = 0;
int i = 0;
int j = 0;
/* Your solution goes here */
return;
}
}
Explanation / Answer
NestedLoop.java
public class NestedLoop{
public static void main (String [] args) {
int userNum = 0;
int i = 0;
int j = 0;
/* Your solution goes here */
java.util.Scanner in = new java.util.Scanner(System.in);
System.out.println("Please enter userNum value: ");
userNum = in.nextInt();
String s = "";
for(i=0; i<=userNum; i++){
for(j=0; j<i; j++){
s = s + " ";
}
s = s + i + " ";
}
System.out.println(s);
return;
}
}
Output:
Please enter userNum value:
3
0
1
2
3
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.