Input: a2b4c3
Output: aabbbbccc
Here is my code………which has wrong output:
import java.lang.*; import java.util.ArrayList; class hi { public static void main(String[] args) { String a="a2b4c3"; String alpha=""; ArrayList<Character> num=new ArrayList<Character>(); for(int i=0;i<a.length();i++) { char c=a.charAt(i); if(Character.isDigit(c)==true) { num.add(c); } else { alpha+=c; } } for(int y=0; y<num.size(); y++) { for(int z=0; z<num.get(y); z++) { System.out.print(alpha.charAt(y)); } } } }
Whats wrong in this code, I didn’t get the output as expected
My output is: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb ccccccccccccccccccccccccccccccccccccccccccccccccccc
Need corrections or code in java
Advertisement
Answer
Hi Here your answer.
import java.lang.*; import java.util.ArrayList; class Hi { public static void main(String[] args) { String a="a2b4c3"; String alpha=""; ArrayList<Character> num=new ArrayList<Character>(); for(int i=0;i<a.length();i++) { char c=a.charAt(i); if(Character.isDigit(c)==true) { num.add(c); } else { alpha+=c; } } for(int y=0; y<num.size(); y++) { int count=Integer.parseInt(String.valueOf(num.get(y))); for(int z=0; z<count; z++) { System.out.print(alpha.charAt(y)); } } } }
Or
import java.lang.*; import java.util.ArrayList;
class Hi { public static void main(String[] args) { String a="a2b4c3"; String alpha=""; ArrayList<Integer> num=new ArrayList<>(); for(int i=0;i<a.length();i++) { char c=a.charAt(i); if(Character.isDigit(c)==true) { num.add(Integer.parseInt(String.valueOf(c))); } else { alpha+=c; } } for(int y=0; y<num.size(); y++) { for(int z=0; z<num.get(y); z++) { System.out.print(alpha.charAt(y)); } } } }