How do I print the following items on a given line?

Given the input:

a3b4c5

The output should be:

aaabbbbccccc

How did I make this program?

I have a string from a user specified in the input and then it checks to see if its alphabet first.
If it's an alphabet, increase until it reaches the counter number it will be printed on.
I tried to create the same result, but I am getting the following line as output.

Shown result:

Code:

public class Pattern
{
    public static void main(String s[]) throws NumberFormatException, IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s1 = br.readLine();
        char ch[] = s1.toCharArray();
        for (int i = 0; i < ch.length;) {
            if ((ch[i] <= 65) || (ch[i] >= 90)) {
                i++;
            } else if ((ch[i] <= 97) || (ch[i] >= 122)) {
                i++;
            } else {
                if (ch[i] == '0' || ch[i] == '1' || ch[i] == '2'
                        || ch[i] == '3' || ch[i] == '4' || ch[i] == '5'
                        || ch[i] == '6' || ch[i] == '7' || ch[i] == '8'
                        || ch[i] == '9') {
                    for (int p = 0; p < ch[i]; p++) {
                        System.out.println(ch[i - 1]);

                    }
                }
                i++;
            }
        }
    }
}

      

+3


source to share


6 answers


You are treating inequality correctly and you are not accepting correct logical operators. In addition, you need to print

instead println

, and println

at the very end. You should have something like this.



import java.io.IOException;
import java.lang.NumberFormatException;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class t1

{
    public static void main(String s[]) throws NumberFormatException, IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s1 = br.readLine();
        char ch[] = s1.toCharArray();
        for (int i = 0; i < ch.length;) {
            if ((ch[i] >= 65) && (ch[i] <= 90)) {
                i++;
            } else if ((ch[i] >= 97) && (ch[i] <= 122)) {
                i++;
            } else {
                if (ch[i] >= '0' && ch[i] <= '9') {
                    for (int p = 0; p < ch[i]-'0'; p++) {
                        System.out.print(ch[i - 1]);

                    }
                }
                i++;
            }
        }
        System.out.println("");
    }
}

      

+1


source


Sample code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Pattern
{
    public static void main(String s[]) throws NumberFormatException, IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter input string: ");
        String inputStr = br.readLine();

        ArrayList<String> stringParts = new ArrayList<>();
        Matcher matcher = Pattern.compile("\\D+|\\d+").matcher(inputStr);
        while (matcher.find())
        {
            stringParts.add(matcher.group());
        }

        // Just to view the contents
        System.out.println("stringParts: " + Arrays.toString(stringParts.toArray()));

        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < stringParts.size(); i += 2) {
            for(int j = 0; j < Integer.parseInt(stringParts.get(i + 1)); j++) {

                sb.append(stringParts.get(i));
            }
        }

        System.out.println("Output: " + sb.toString());
    }
}

      

Input / Output:

Enter input string: a3b4c5
stringParts: [a, 3, b, 4, c, 5]
Output: aaabbbbccccc

Enter input string: ab2cd3
stringParts: [ab, 2, cd, 3]
Output: ababcdcdcd

Enter input string: abc1def2xyz3
stringParts: [abc, 1, def, 2, xyz, 3]
Output: abcdefdefxyzxyzxyz

      




  • Using pattern matching, split the input string into alphabets and numbers
  • Use a string builder to add them accordingly.


Note:

It must be some form of run length encoding or decoding in this case.

+3


source


This should fix your problem.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char ch[] = br.readLine().toCharArray();

for (int i = 1; i < ch.length; i++) {
    if (Character.isDigit(ch[i])) {
        for (int j = 0; j < ch[i]-'0'; j++) {
            System.out.print(ch[i-1]);
        }
    }
}

      

Basically, by having a single if statement that checks if ch [i] is a digit or not, you avoid doing all of your other checks. If ch [i] is a digit, convert it to an integer by subtracting the character "0" from it. The rest should make sense.

+2


source


Here's a shorter example using regex

and capture groups. This is done on the assumption that sometimes you may have a pattern where there is a line that does not have a number following it.

For example:

a2bc3 => aabccc

      

Regular Expression Pattern:

"(\\D+)(\\d*)"

      

Breakdown of structure:

  • (\\D+)

    - captures 1 or more insignificant characters in capture group 1
  • (\\d*)

    - captures 0 or more digits of characters in capture group 2

Use StringBuilder

to create output.

Convert Capture Group 2 to Integer if Group 2 has data, so you know how many times to repeat Group 1 in the results.

public static void main(String[] args) throws Exception {
    List<String> inputs = new ArrayList() {{
       add("a3b4c5");
       add("a3bc5");
       add("a3bc");
       add("abc");
       add("ab3cd4ef5");
       add("a10bc1e10");
    }};

    for (String input : inputs) {
        StringBuilder output = new StringBuilder();

        Matcher matcher = Pattern.compile("(\\D+)(\\d*)").matcher(input);
        while (matcher.find()) {
            String group1 = matcher.group(1);
            String group2 = matcher.group(2);

            int loopCount = 0;
            if (!group2.isEmpty()) {
                loopCount = Integer.parseInt(group2);
            }

            // Always print the group at least once
            output.append(group1);
            // Possibly print more
            for (int i = 1; i < loopCount; i++) {
                output.append(group1);
            }   
        }
        System.out.println(output);
    }
}

      

Results:

aaabbbbccccc
aaabcbcbcbcbc
aaabc
abc
abababcdcdcdcdefefefefef
aaaaaaaaaabceeeeeeeeee

      

+2


source


The first two if statements mean that you are missing anything less than or equal to 97 or greater than or equal to 90: therefore, you will miss all possible values.

You probably just want to use Character.isLetter()

and Character.isDigit()

.

Also, there p < ch[i]

should be p < (Integer.valueOf("" + ch[i]))

; otherwise, 1 will print 49 copies.

+1


source


I tried like this, it may not be the best, but you can try with this

   String st="A3B4C5";
    String st1="";
    int l=0;
    char ar[]=st.toCharArray();
    char c='0';
    for(int i=0;i<ar.length;i++){
    if(Character.isLetter(ar[i])){
    c=ar[i];
        }
    else if(Character.isDigit(ar[i])) {
     l=Character.getNumericValue(ar[i]);     
    for(int j=0;j<l;j++){
    System.out.print(c);
    }   
        }

    }

      

0


source







All Articles