gpt4 book ai didi

java - 代码似乎处于无限循环中,无法识别位置

转载 作者:行者123 更新时间:2023-12-01 18:32:12 25 4
gpt4 key购买 nike

我正在尝试解决以下问题,CCC '13 J3 - From 1987 to 2013 .

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;
}
}
}
}

最佳答案

  1. 您需要:if(!same) {/*如果不相同则代码*/}
    same = falsefalse 赋给 same 并返回 same 的新值:false >

  2. 您可以在 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);
}
}

关于java - 代码似乎处于无限循环中,无法识别位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60141086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com