lundi 22 mai 2017

How do I get my code to properly use numbers with a different amount of digits?

This program searches for the next smallest number, whose digits are in an ascending order. It works alright, but it of course doesn't work for numbers that don't have three digits, because my if-statements don't scale. How could I set them up to do so?

import java.util.ArrayList;
import java.util.Arrays;
public class Main{
     public static void main(String[] args){
        String String="143";
        int Zahl = Integer.parseInt(String);
        for(int j=0; j<1000;j++){
            int digitscount=0;
            if(Zahl>9){
                int NeueZahl = Zahl;
                ArrayList<Integer> List = new ArrayList<Integer>();
                while (NeueZahl > 0) {
                    List.add(NeueZahl % 10);
                    NeueZahl = NeueZahl / 10;
                    digitscount++;
                }
                int[] ret = new int[List.size()];
                int a=List.size()-1;
                for (int i=0; i < List.size(); i++){
                    ret[i] = List.get(a).intValue();
                    a--;
                }
                if(ret[0]>ret[1]||ret[1]>ret[2]){
                    Zahl--;
                }
                if(ret[0]<ret[1]&&ret[1]<ret[2]){
                    System.out.println(Zahl);
                    break;
                }
            }
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire