Search code examples
javanested-loopsalphabetical

How do I format these nested loops in Java?


The Goal

Hello! I am trying to learn how to use nested for loops in AP Computer Science at school, and I am having trouble with this lab :/ I have made some progress towards getting the correct result. However, I am having issues on my path. The image above shows what I need to do.

Sample Data:

C 4

A 5

Sample Output:

CCCC DDD EE F

CCCC DDD EE

CCCC DDD

CCCC


AAAAA BBBB CCC DD E

AAAAA BBBB CCC DD

AAAAA BBBB CCC

AAAAA BBBB

AAAAA

also above is the I/O I need.

The code I have written so far is as follows:

import java.util.Scanner;

public class LettersAndNumbers {
    public static void main(String args []) {
    int times;
    String character;//I know this sounds stupid
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter a character and integer");
    character = scan.nextLine();
    times = scan.nextInt();

    String output ="";
    for(int i=times; i>=0;i--) {
        for(int j=i;j>=1;j--){
            for(int x = j; x>=1; x--)
            {
                output=output + character;


            }
            output=output+" ";

        }           
        output=output +'\n';
        int charValue = character.charAt(0);
        character = String.valueOf( (char) (charValue + 1));    
    }
    System.out.println(output);
  }
}

It yields the following output (I'm getting close):

Enter a character and integer C

4

CCCC CCC CC C

DDD DD D

EE E

F

Any help you can provide is greatly appreciated!


Solution

  • Working solution:

    Scanner scanner = new Scanner(System.in);
        String userInputChar=scanner.next();
        char userChar=userInputChar.charAt(0);      
        int userInputDigit=scanner.nextInt();       
        for(int i=1;i<=userInputDigit;i++){
            char charProcess=userChar;          
            for(int j=(userInputDigit-i)+1,l=userInputDigit;j>=1;j--,l--){              
                for(int k=l;k>=1;k--){
                    System.out.print(charProcess);
                }
                charProcess=(char) (charProcess+1);
                System.out.print(" ");              
            }
            System.out.print("\n");
        }
        scanner.close();
    

    Let me know how it goes. Good Luck.