2个循环1递减变量

时间:2014-09-23 04:26:47

标签: java loops for-loop while-loop

我有一个调用输入整数的赋值,然后将该整数减少到1。

它必须使用while循环将该数字一直显示为1,而在另一行上使用for循环来执行相同操作。

现在,在我启动while循环之后,for循环的输出不会显示。显然因为在while循环之后startNum现在设置为0。

如何解决这个问题,以便能在两条线上显示减少的数字? 我现在的代码:

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 个答案:

答案 0 :(得分:1)

startNum循环之前有另一个变量将for重置为原始值

// ...
int startNum = input.nextInt(); 
int reset = startNum;
// ...
startNum = reset;
for (int x = 0; x < startNum; x++)
// ...

答案 1 :(得分:1)

由于Java支持OOP中的Java原语按值传递

为什么不创建一个类并将其命名为Num

public class Num {

        private int startNum;

        public Num() {

            startNum = 0;
        }

        public int getStartNum() {
            return startNum;
        }

        public void setStartNum(int startNum) {
            this.startNum = startNum;
        }
}

Dirver类成为:

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 + " ");

        }

    }

输出:

Enter a number: 8
WHILE LOOP: 
8 7 6 5 4 3 2 1 
FOR LOOP:
0 1 2 3 4 5 6 7

答案 2 :(得分:0)

这样做:

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 + " ");

        }

    }