2 cycles 1 reduced variable
I have an assignment that calls an input integer and then decreases that integer down to 1.
it should use a while loop to display that number up to 1 and on another line using a for loop to do the same.
Now, after I started the while loop, my output for the for loop is not displayed. Obviously because startNum is now set to 0 after the while loop.
How can I get around this so that I can show thumbnails on both lines? The code I currently have:
public class CountDown
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int startNum = input.nextInt();
System.out.println("WHILE LOOP: ");
while (startNum > 0)
{
System.out.print(startNum + " ");
startNum--;
}
System.out.println("\nFOR LOOP:");
for (int x = 0; x < startNum; x++)
{
System.out.print(startNum + " ");
}
}
}
+3
source to share
3 answers
Since Java supports OOP
and primitives are passed by value to Java
.
why not create a class and name it Num
,?
public class Num {
private int startNum;
public Num() {
startNum = 0;
}
public int getStartNum() {
return startNum;
}
public void setStartNum(int startNum) {
this.startNum = startNum;
}
}
The Dirver class will become:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Num n = new Num();
System.out.print("Enter a number: ");
n.setStartNum(input.nextInt());
System.out.println("WHILE LOOP: ");
int counter = n.getStartNum();
while (counter > 0) {
System.out.print(counter + " ");
counter--;
}
System.out.println("\nFOR LOOP:");
for (int x = 0; x < n.getStartNum(); x++) {
System.out.print(x + " ");
}
}
output:
Enter a number: 8
WHILE LOOP:
8 7 6 5 4 3 2 1
FOR LOOP:
0 1 2 3 4 5 6 7
+1
source to share
do the following:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int startNum = input.nextInt();
System.out.println("WHILE LOOP: ");
int temp = startNum; // store startNum in temp variable
while (startNum > 0) {
System.out.print(startNum + " ");
startNum--;
}
System.out.println("\nFOR LOOP:");
for (int x = temp; x >0 ; x--) { // here iterate through temp.
System.out.print(x + " ");
}
}
0
source to share