0

I'm trying here to segregate o's and 1's in a java String and print the result as such 0's will print at first and then 1's will print here's my code:

 int len = scanner.nextInt();
    String num = scanner.nextLine();
    StringBuilder result = new StringBuilder("");
    for(int i = 0;i < len-1;i++){
        if(num.charAt(i) == '0'){
            result.append("0");
        }
    }
    for(int i = 0;i < len-1;i++){
        if(num.charAt(i) == '1'){
            result.append("1");
        }
    }
    System.out.print(result);

input should be like this:

5
11010

and the output should be:

00111

but in the above I'm getting error as java.lang.StringIndexOutOfBoundsException: String index out of range:

Ajax
  • 179
  • 1
  • 13

2 Answers2

3

You need a scanner.nextLine() after the int len = scanner.nextInt() to pick up the new line characters at the end of the line.

You should also start your loops at 0, as you are skipping the first character.

Rarblack
  • 4,160
  • 4
  • 17
  • 31
  • This is not an answer. Use comment instead. – Rarblack Aug 10 '19 at 18:50
  • 2
    This is what is wrong with their code. They are given the length of the string, and they are choosing to use the length of the string given. If you don't include a scanner.nextLine() after a scanner.nextInt() if the int is on its own line, then the next nextLine() method called will pick up the new line character instead of picking up the string. This is the correct answer, the comment is an alternative that does not address the true problem they are having – BeyondPerception Aug 10 '19 at 18:56
1

You should start declaring your i's to 0, since array's start at 0 and you want to check every element of the given string. Also, you want to loop until i reaches the end of the string.

int _ = scanner.nextInt(); // obsolete 
String num = scanner.nextLine();
StringBuilder result = new StringBuilder("");

    for(int i = 0;i < num.length(); i++){
        if(num.charAt(i) == '0'){
            result.append("0");
        }
    }
    for(int i = 0;i < num.length(); i++){
        if(num.charAt(i) == '1'){
            result.append("1");
        }
    }
    System.out.println(result.toString());
Alessandro
  • 633
  • 1
  • 7
  • 18