Closed. This question is not reproducible or was caused by typos。它当前不接受答案。












想改善这个问题吗?更新问题,以使溢出。

4个月前关闭。



on-topic





我正在尝试解决以下问题 Improve this question

You might be surprised to know that 2013 is the first year since 1987 with distinct digits.
The years 2013, 2015, 2016, 2017, 2018, 2019 each have distinct digits.
2012 does not have distinct digits, since the digit 2 is repeated.

Given a year, what is the next year with distinct digits?


看来我的代码(在Java中)在某个地方进入了无限循环,但是我无法确定我的代码执行此操作的确切位置和原因。如果输入“ 1987”,则程序将继续运行,而不会输出遵循上述条件的下一年(所有数字均不同的下一年)。我该如何解决?

这是我的代码供参考。

import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);

        int yearInt = input.nextInt();
        yearInt+=1;

        input.close();

        boolean check = true;

        while(check==true){

            String yearString = Integer.toString(yearInt);

            String [] numsString = yearString.split("");
            int l = numsString.length;
            int [] nums = new int [l];

            for(int i=0; i<l;i++){
                nums[i] = Integer.parseInt(numsString[i]);
            }

            Arrays.sort(nums);

            boolean same = false;

            for(int i=0;i<l-1; i++){
                if(nums[i]==nums[i+1]){
                    same = true;
                }
            }

            if (same = false){
                check = false;
                System.out.println(yearInt);
            }
            else{
                yearInt+=1;
            }
        }
    }
}

最佳答案

您需要:if(!same) {/*code if not same*/}
same = falsefalse分配给same并返回same的新值:false
您可以在while循环中使用break;


while(true)
{
    if(/*is finished*/) { break; }
}
//code when finished


总结

import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) {

        Scanner input = new Scanner (System.in);
        int yearInt = input.nextInt();
        input.close();

        while(true){

            yearInt+=1;
            String yearString = Integer.toString(yearInt);

            String [] numsString = yearString.split("");
            int l = numsString.length;
            int [] nums = new int [l];

            for(int i=0; i<l; i++){
                nums[i] = Integer.parseInt(numsString[i]);
            }

            Arrays.sort(nums);

            boolean different = true;

            for(int i=0;i<l-1; i++){
                if(nums[i]==nums[i+1]){
                    different = false;
                }
            }

            if (different){
                break;
            }
        }
        System.out.println(yearInt);
    }
}

09-26 15:37