我们可以在 if 语句中从一个字符串中取出两个字符串吗?

Can we take two string from one String in if statement?

我想打印最大和最小的两个字符串词典。打印最大但最小的输出与最大的输出相同。我的代码有什么问题?

public class 解决方案{

public static String getSmallestAndLargest(String s, int k) {
   String sequence = s.substring(0,k);
    String smallest = sequence;
    String largest = sequence;

    for(int i=0;i<=(s.length()-k); i++){

        sequence= s.substring(i,(i+k));

        if    (sequence.compareTo(smallest)<0){
            sequence=smallest;
        }
        if (sequence.compareTo(largest)>0){
            sequence=largest;
        }

            }
    // Complete the function
    // 'smallest' must be the lexicographically smallest substring of length 'k'
    // 'largest' must be the lexicographically largest substring of length 'k'

    return smallest + "\n" + largest;
}




public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String s = scan.next();
    int k = scan.nextInt();
    scan.close();

    System.out.println(getSmallestAndLargest(s, k));
}

}

if(sequence.compareTo(smallest)<0){
    smallest = sequence;
}
if (sequence.compareTo(largest)>0){
    largest = sequence;
}

您正在将 sequencesmallestlargest 进行比较。而你的 sequencefor loop 的每次迭代中都会发生变化。在 if condition 中,您正在检查您当前的 sequence 是否比您的 smallestlargest smaller/larger,如果是,您必须更新您的 smallestlargest 值。

    if (sequence.compareTo(smallest)<0){
        smallest=sequence;
    }
    if (sequence.compareTo(largest)>0){
        largest=sequence;
    }

在Java语言中,变量赋值是这样进行的。

variable = value;