使用" while循环"对于字符串

时间:2016-03-14 09:18:52

标签: java

import java.util.Scanner;
class example{

    static String next(String base, String n, String m){

        while(m >= n){

            for(int i= n.length()-1; i>=0; i--){
                //i= n.length()-1;
                char digit= n.charAt(i);
                int pos= base.indexOf(digit);

                if(n.charAt((n.length())-1) == 0){
                    n= n.substring(0,i)
                    + base.charAt(pos+1)
                    + n.substring(i+1);

                    break;
                }//if end

                if(pos == base.length()-1){
                    n= n.substring(0,i)
                    + base.charAt(0);

                }//if end

                else{

                    n= n.substring(0,i)
                    + base.charAt(pos+1)
                    +n.substring(i+1);

                    break;
                }//else end

            }//for end

            return n;   
        }//while end

    }//next end

        public static void main(String[] args){

            System.out.print("Enter the Base: ");
            Scanner input= new Scanner(System.in);
            String base= input.nextLine(); //base number
            System.out.print("Enter Starting Number: ");
            String n= input.nextLine(); // starting number
            System.out.print("Enter the Last Number: ");
            String m= input.nextLine(); //last number

            System.out.println(next(base,n,m));

    }//main end
}//class end

有没有办法让这成为可能?我需要在字符串n和m之间打印结果,但是while循环不起作用,因为它们都是字符串。如果我将字符串切换为int和back,因为我将它们更改为循环外部的int,它们不会保持整数。任何解决方案?

1 个答案:

答案 0 :(得分:0)

由于你想找到nm之间的字符串,这两个字符串都出现在base中,你可以找到两个字符串的索引并查找子字符串使用前面找到的索引的base字符串的-string。

base.substring(base.indexOf(n)+n.length(), base.indexOf(m)-1);

Click用于演示。