Jason37 Jason37 - 1 month ago 8
Java Question

How do I make it so my code displays a cerrtain amount of lines (like it does) but backwards

So when I enter 4, instead of say 4 bottles of beer etc, It will start with 100 and go to 96 and then stop (ending with the final line)

import java.util.Scanner;

public class ThreeDotNine {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("How many Verses would you like to print: ");
String num = sc.nextLine();
int num2 = Integer.parseInt(num);
String s = " ";

for (int x = num2; x > 0; x--) {
System.out.println(x + " bottles of beer on the wall " + x + " bottles of beer");
System.out.println("Take one down, pass it around, " + (x - 1) + " bottles of beer on the wall.\n");
}
System.out.print("Go to the store, buy some more, ");
System.out.println("99 bottles of beer on the wall.\n");

}
}

5im 5im
Answer

I would try it like that:

for ( int x = 0; x <= num2; x++ ) {
  int y = 100 - x;

  System.out.println(y + " bottles of beer on the wall " + y + " bottles of beer");
  System.out.println("Take one down, pass it around, " + (y - 1) + " bottles of beer on the wall.\n");
}

It's easier to understand if you define a second variable.

Now you have your output with 100 99 98 97 96

Comments