Вы собираетесь автоматизировать известную песню «99 Bottles of XXX on the wall». Вы распечатаете текст ВСЕХ 99 куплетов песни. Используйте цикл! Если не знаешь слов, поищи в гугле.

Программа должна:

  1. Спросите пользователя об его возрасте

  2. Если пользователю 21 год или больше, спросите его, предпочитает ли он пиво или газировку.

А. Если им меньше 21 года ИЛИ они предпочитают газировку, то текст песни звучит так: «99 бутылок газировки на стене».

Б. Если им больше 21 года, то это «99 бутылок пива».

НЕОБХОДИМО ИСПОЛЬЗОВАТЬ ЦИКЛ WHILE LOOP, а переменная счетчика должна быть частью распечатать заявление!

Итак, первый куплет будет таким:

99 бутылок газировки на стене

99 бутылок газировки

Если одна из этих бутылок упадет со стены

…..98 бутылок газировки на стене

Последний стих:

1 бутылка газировки на стене

1 бутылка газировки

Если эта одинокая бутылка газировки упадет со стены

Никаких бутылок газировки на стене!

Итак, подумайте, что вам нужно добавить в свой цикл, чтобы напечатать последний куплет с немного другим текстом?

// вот мой код. Когда я запускаю его, последний текст появляется вот так

1 of beer on the wall
 1 bottles of beer
 If one of those bottles should fall off the wall
 ...0 bottles of beer on the wall
 0 of beer on the wall
 0 bottles of beer
 If that lone bottle of beer should fall off the wall
 No bottles of beer on the wall

// как я могу сделать так, чтобы часть бутылки "0" не отображалась??

Scanner user = new Scanner(System.in);

           int age, beverage;


           System.out.println("Please type in your age");
           age = user.nextInt();

           user.nextLine();
           System.out.println("Would you like soda or beer? soda=1 beer=2");
           beverage = user.nextInt();

        if(age<21 || beverage==1)
           {
           int bottles = 99;
            while( 1<= bottles){
                System.out.println(bottles+" of soda on the wall");
                System.out.println(bottles+" bottles of soda");
                System.out.println("If one of those bottles should fall off the wall");
                bottles--;
                System.out.println("..."+bottles+" bottles of soda on the wall");
            if(bottles==0){
                System.out.println(bottles+" of soda on the wall");
                System.out.println(bottles+" bottles of soda");
                System.out.println("If that lone bottle of soda should fall off the wall");
                System.out.println("No bottles of soda on the wall");
            }
        }
    }
        if(age>=21 && beverage == 2)
        {
            int bottles=99;
            while(1<= bottles){
                System.out.println(bottles+" of beer on the wall");
                System.out.println(bottles+" bottles of beer");
                System.out.println("If one of those bottles should fall off the wall");
                bottles--;
                System.out.println("..."+bottles+" bottles of beer on the wall");
            if(bottles==0){
                System.out.println(bottles+" of beer on the wall");
                System.out.println(bottles+" bottles of beer");
                System.out.println("If that lone bottle of beer should fall off the wall");
                System.out.println("No bottles of beer on the wall");
            }
        }
    }

        }
    }
-2
Hyunseok Song 12 Ноя 2014 в 04:47
Одним из требований было спрашивать пользователя о газировке или пиве только в том случае, если ему 21 год или больше. Затем покажите газировку, если им меньше 21 года, или попросите газировку.
 – 
Jason
12 Ноя 2014 в 04:54
Можете ли вы объяснить более подробно, пожалуйста?
 – 
Hyunseok Song
12 Ноя 2014 в 07:00
Я прокомментировал ваш исходный вопрос, а не тот, в который вы его отредактировали. Пожалуйста, не меняйте один вопрос на другой, поскольку люди помогают вам; если у вас есть другие вопросы, отметьте правильный ответ как принятый и задайте другой вопрос.
 – 
SJuan76
12 Ноя 2014 в 10:21

2 ответа

Я полагаю, что у вас изменены условия проверки цикла. Кроме того, я бы реализовал это с помощью printf, используя Formatter синтаксис. Затем вы можете включить напиток в формат. Это работает, если я запускаю его так,

public static void main(String[] args) {
    Scanner user = new Scanner(System.in);
    int bottles = 99;

    System.out.println("Please type in your age");
    int age = user.nextInt();
    System.out.println("Would you like soda or beer? soda=1 beer=2");
    int beverage = user.nextInt();
    String drink = (age >= 21 && beverage == 2) ? "beer" : "soda";
    while (bottles > 1) { //  <-- swap 1 and bottles.
        System.out.printf("%d bottles of %s on the wall%n", bottles, drink);
        System.out.printf("%d bottles of %s%n", bottles, drink);
        System.out.println("If one of those bottles "
                + "should fall off the wall");
        bottles--;
        System.out.printf("... %d bottles of %s on the wall.%n", bottles,
                drink);
    }
    System.out.printf("%d bottle of %s on the wall%n", 1, drink);
    System.out.printf("%d bottle of %s%n", 1, drink);
    System.out.printf("If that lone bottle of %s should fall off the wall%n",
                drink);
    System.out.printf("No bottles of %s on the wall!%n", drink);
}
0
Elliott Frisch 12 Ноя 2014 в 05:00
 if(age>=21 && beverage==2)
       int bottles = 99; /* initialize bottles here*/
0
Billy_Bob 12 Ноя 2014 в 05:07
Это не должно иметь значения. Почему это было принято? Это действительно что-то сделало?
 – 
Reinstate Monica -- notmaynard
12 Ноя 2014 в 06:51