title: Given an integer N. What is the smallest integer greater than N in java
body: <p>I was trying to write a code that takes an integer between 1 and 1_000_000 and gives back the smallest integer greater than that with the same digits, and if it doesn't exist, it prints 0.</p>
  <p>For example</p>
  <p>input: 156</p>
  <p>output 165</p>
  <p>input 330</p>
  <p>output 0</p>
  <p>input 27711</p>
  <p>output 71127</p>
  <p>My problem is, my code below doesn't return the correct output for other inputs.</p>
  <p>For example, in input 4231, the output should be 4312.</p>
  <p>I'm having trouble finding the best algorithm that returns the correct output for every input.</p>
  <p>tnx in advance</p>
  <pre><code>import java.util.Scanner;
  
  public class Test4 {
  
  public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      String x = sc.nextLine();
      char[] chars = new char[x.length()];
      char[] oldChars = new char[x.length()];
  
  
      char temp;
      for (int i = 0; i &lt; x.length(); i++) {
          chars[i] = x.charAt(i);
          oldChars[i] = chars[i];
      }
  
  
      if (x.length() &gt; 3){
          for (int j = 0; j &lt; x.length(); j++) {      
              if (chars[0] &lt; chars[j]) {
                  temp = chars[0];
                  chars[0] = chars[j];
                  chars[j] = temp;
                  break;
              }
          }
  
          for (int j = 1; j &lt;= x.length() ; j++) {           
              for (int i = 1; i &lt; x.length() - 1; i++) {
                  if (chars[i] &gt; chars[i+1]){
                      temp = chars[i];
                      chars[i] = chars[i+1];
                      chars[i+1] = temp;
                  }
              }
          }
          for (int i = 0; i &lt; x.length(); i++) {
              System.out.print(chars[i]);
          }
      }
      
      else if (x.length() == 1)
          System.out.println(0);
  
      else {
              temp = chars[x.length()-2];
              chars[x.length()-2] = chars[x.length()-1];
              chars[x.length()-1] = temp;
              if (chars[x.length()-2] &gt; oldChars[x.length()-2])
                  for (int i = 0; i &lt; x.length(); i++) {
                      System.out.print(chars[i]);
                  }
              else
                  System.out.println(0);
      }
      
  
      sc.close();
  }
  </code></pre>
  <p>}</p>