gpt4 book ai didi

java - 调用方法时无限循环

转载 作者:太空宇宙 更新时间:2023-11-04 06:27:36 25 4
gpt4 key购买 nike

当我尝试在冒泡排序代码中使用 Compare 方法来确定要排序的字符串的字母顺序时,我陷入了 Compare 方法中的无限循环,否则该方法会起作用。

有什么想法吗?谢谢!

public static int Compare(String s1 , String s2) { //compares two strings alphabetically
int result = 0 ;
String newS1 = "";
String newS2 = "";

for (int i = 0; i< s1.length(); i++){ //loop converts strings from uppercase to lowercase
char s1Char = s1.charAt(i);
if (65 <= s1Char && s1Char <=90){
s1Char = (char)( (s1Char + 32) );
}
newS1 = newS1 + s1Char;
}

for (int i = 0; i< s2.length(); i++){
char s2Char = s2.charAt(i);
if (65 <= s2Char && s2Char<=90){
s2Char = (char)( (s2Char + 32) );
}
newS2 = newS2 + s2Char;
}

for (int i = 0 ; i <newS1.length();){ //compares the two lowercase strings by ascii value
if (newS1.charAt(i) < newS2.charAt(i)){
result = -1 ;
System.out.println(newS1+ " is before " +newS2+ " in the dictionary");
break ;
}
if (newS1.charAt(i) > newS2.charAt(i)){
result = 1 ;
System.out.println(newS2+ " is before " +newS1+ " in the dictionary");
break ;
}
if (newS1.charAt(i) == newS2.charAt(i)) {
i++ ;
}
else {
result = 0 ;
System.out.println("The words are the same.");
break ;
}
}
return result ;
}

public static int bubbleSort(String[] input_array) { //sorts an array alphabetically
int n = input_array.length ;
String temp = "" ;
int comparisons = 0 ;
boolean swap = false ;
while (swap == true) {
swap = false ;
for(int i = 1 ; i < input_array.length - 1 ; ){
if(Compare(input_array[i] , input_array[i+1]) == -1) { //use compare method above
comparisons++ ;
temp = input_array[i] ;
input_array[i] = input_array[i-1] ; //swap if sorting needed
input_array[i-1] = temp ;
swap = true ;
System.out.println(input_array);
i++ ;
}
else {
i++ ;
}
}
}
return comparisons;
}

public static void main(String[] args) { // used to test code
String[] testArray = {"b" , "c" ,"e" , "d"} ;
bubbleSort(testArray) ;
}

最佳答案

在这里,您将 swap 指定为等于 true。

 while (swap = true) {

我猜你想比较它。

boolean swap = true;
while (swap == true){ //Or better while (swap){
swap = false;

关于java - 调用方法时无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26575286/

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