1

My project is to show lines with cardinals, from an initial number and then varying this number to another number entered. It starts by asking for a initial number of cardinals (the output must be "###" the number of times asked) and then ask for the final number of cardinals to add. So case, click here 5 initial cardinals and add 3, the program must show a line with 5, another with 6, another with 7 and another with 8 cardinals. How do I add the cardinals? With if-else?

import java.util.Scanner;

public class P02Cardinais {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter the number inicial of cardinals: ");
        int numCardinais = keyboard.nextInt();  
        System.out.println("Enter the number of cardinals to add: ");
        int numCardinaisAdd = keyboard.nextInt();

        int i;
        for (i = 0; i < numCardinais; i++) {
            System.out.print("#");
        } System.out.print(" - " + numCardinais);

        keyboard.close();
    }
}

Example of the output

(number inicial - 2 ; number to add - 3)
## - 2
### - 3
#### - 4
##### - 5

1 Answers1

1

You need 2 loops

  • one for the number of lines from initial to initial+add
  • one for the number of # which has to be the index of first loop (limo of j is i)

for (int i = numCardinais; i <= numCardinais+numCardinaisAdd; i++) {
    for (int j = 0; j<i; j++) {
        System.out.print("#");
    } 
    System.out.println(" - " + i); // new line and index
} 
azro
  • 53,056
  • 7
  • 34
  • 70