Java计数器循环

时间:2013-02-17 18:54:18

标签: java

我对编程非常陌生,并试图掌握如何在Java中倒计时的想法。

我想运行一个程序,要求您输入以下格式输入的5首歌曲:

Please enter song 1: "Thriller"
Choose 4 more songs.

所以我从5点回到1点,我可以得到一些关于如何做到这一点的想法吗?以下是我的不良尝试,但请注意我的计数器增加(这不是我想要的)。

import java.util.Scanner;

public class testing {  
    public static void main(String[] args) {
        String song;
        int amount = 0;
        Scanner kdb = new Scanner(System.in);
        while (amount < 5) {
            System.out.println("enter song:");
            song = kdb.next();
            amount++;
            System.out.println("you chose " + song + amount + " more required");
        }
    }
}

2 个答案:

答案 0 :(得分:1)

更改amount++(与amount = amount + 1相同)。它应该是amount--(与amount = amount - 1相同)。

重写程序(for循环):

import java.util.Scanner;

public class Test {
    public static void main(String... args) {
        String song;
        Scanner kdb = new Scanner(System.in);
        for (int amount = 5; amount > 0; amount--) {
            System.out.println("Enter song:");
            song = kdb.next();
            System.out.println("You chose " + song + ". Choose" + amount + " more");
        }
    }
}

答案 1 :(得分:0)

这是我将如何做到的,

 public static void main(String[] args) {
        // TODO Auto-generated method stub
        String song;
        int amount = 1;
        Scanner kdb = new Scanner(System.in);
        while (amount <= 5) {
            System.out.println("enter song:");
            song = kdb.next();
            if(amount<5){
            System.out.println("you chose " + song + amount + " more required");
            }
            ++amount;
        }

    }