0

I wanna create a program that takes input from the user like : 's' means "*" and I want to print it x times. For example if user inputs 4s , the result should be **** or something like that 2s4s : ****** . I tried to user charAt function but could not handle with the numbers ...

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner input = new Scanner(System.in);

    System.out.println("Welcome to image printer program.");

    System.out.print("Please enter your sequence:");

    String sequence = input.nextLine();

    char b = ' ';

    int s = 's';

    char n = '\n';

    for (int a = 0; a <= sequence.length() - 1; a++) {

        char c = sequence.charAt(a);

        if (c == 's') {

            System.out.print("*");

        }

    }

}

2 Answers2

0

It seems silly to give you the answer outright, so instead I can give you an idea of an approach.

The problem statement

So the syntax you have defined is <count>s<count>s.... That means that for every s, there should be a <count>.

Step 1 - Grabbing the counts.

You start with a String like s1s2s3s4. You split that string on the letter s which gives you:

["1","2","3","4"]

Step 2 - Adding up those counts.

You want to find out how many stars you have in total, which is the sum of all of the counts. You need to add those numbers together.

1 + 2 + 3 + 4 = 10

Step 3 - Printing the stars.

I'm guessing you can see where to go from here.

christopher
  • 26,815
  • 5
  • 55
  • 89
  • "It seems silly to give you the answer outright" Yes you are right. Thank you for your help. –  Nov 15 '18 at 20:11
0

Use Character.isDigit and Character.isLetter methods:

    int count = 0;
    boolean isLetter = false;
    String symbol = "*";
    String s = input.next();

    for (int i = 0; i < s.length(); i++) {
        char character = s.charAt(i);
        if (Character.isDigit(character)) {
            count = Character.getNumericValue(character);
        } else if (Character.isLetter(character)) {
            isLetter = true;
        }

        if (count != 0 && isLetter) {
            for (int j = 0; j < count; j++) {
                System.out.print(symbol);
            }
            count = 0;
            isLetter = false;
        }
    }
Centos
  • 250
  • 3
  • 13