使用 for 循环和 if 语句检查字谜的 Java 应用程序

我正在为大学做另一项编码任务。我在使用 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));

    }

}


长风秋雁
浏览 187回答 2
2回答

慕丝7291255

将 if 语句中的条件更改为 if (phrase.charAt(i) == alphabet)或者您可以使用以下函数来检查两个字符串字谜boolean checkAnagram(String st1, String st2){&nbsp; &nbsp;int arr[]=new int[26];&nbsp; &nbsp; int l1=st1.length();&nbsp; &nbsp; int l2=st2.length();&nbsp; &nbsp; if(l1!=l2){&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }for(int i=0;i<l1;i++){&nbsp; &nbsp; arr[st1.charAt(i)-97]+=1;&nbsp; &nbsp; arr[st2.charAt(i)-97]-=1;}&nbsp;for(int i=0;i<25;i++){&nbsp; &nbsp; &nbsp;if(arr[i]!=0) return false;&nbsp;}&nbsp; &nbsp; return true;}

ITMISS

我认为问题在于您正在与内循环i的索引 进行比较,您想与外循环的索引 进行比较alphabet。if&nbsp;(phrase.charAt(i)&nbsp;==&nbsp;alphabet)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java