title: Tracing a bug in a "reverse domain" program in Java
body: <p>My code is supposed to reverse a domain. For example, if the input is www.google.com.uk, it should print uk.com.google.www</p>
  
  <p>My problem is that my code prints uk.com..google.www</p>
  
  <p>I can't figure where the extra . comes from or how to remove it. I did some tracing and found that www.stack.com.edu.uk would return uk.edu..com..stack.www</p>
  
  <pre><code>import java.util.*;
  
  public class Domainreverse {
  
  
  
      public static void main(String[] args) {
          Scanner sc = new Scanner(System.in);
          String domain = sc.nextLine();
          int x;
          int start = 0;
          String reversed_domain = "";
          boolean flag = false;
  
  
          do{
  
              x = domain.indexOf(".",start+1);
              if(x==-1){
                  flag = true;
                  break;
              }
              reversed_domain = domain.substring(start,x+1) +reversed_domain;
  
              start = x;
  
  
          } while(flag==false);
          int length = domain.length();
          int z = domain.lastIndexOf(".");
          String enddomain = domain.substring(z+1,length);
          reversed_domain = enddomain+reversed_domain;
          int p = reversed_domain.lastIndexOf(".");
          reversed_domain = reversed_domain.substring(0,p);
  
  
  
          System.out.print(reversed_domain);
  
  
  
      }
  
  }
  </code></pre>