我正在为大学做另一项编码任务。我在使用 for 循环(带有另一个 for 循环和 if 语句)来获取 String 参数并按字母顺序对其重新排序时遇到问题。然后,该任务要求我们相互检查两个短语,以检查这些短语是否为字谜。循环是我坚持的一点。我的 for 循环应该按字母顺序输出第一个短语,但我的 if 语句没有按预期运行。布尔语句不正确,但我不确定我应该检查短语.charAt(i) 以记录该信件的内容。
我们不允许使用数组来完成此任务。
import java.util.Scanner;
public class AnagramApp {
/**Method to reformat string in alphabetical order**/
public static String orderString(String phrase){
String output = "";
for (char alphabet = 'a'; alphabet <='z'; alphabet ++ ){
for (int i = 0; i < phrase.length(); i++){
if (phrase.charAt(i) == i){
output += phrase.charAt(i);
}
}
}
return (output);
}
public static void main(String [] args){
/**Setting scanner object to retrieve user input for both phrases **/
Scanner sc = new Scanner(System.in);
System.out.println("Enter first phrase");
String phrase1 = sc.nextLine();
System.out.println("Enter second phrase");
String phrase2 = sc.nextLine();
/**Send phrases to lower case for parsing to new string in char order**/
phrase1 = phrase1.toLowerCase();
phrase2 = phrase2.toLowerCase();
System.out.println(orderString(phrase1));
System.out.println(orderString(phrase2));
}
}
慕丝7291255
ITMISS
相关分类