简体   繁体   English

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

[英]Java app to check anagram using for loop and if statement

I'm working on another coding task for university. 我正在为大学编写另一个编码任务。 I am having trouble using a for loop (with another for loop and an if statement) to take a String parameter, and reorder it in alphabetical order. 我在使用for循环(与另一个for循环和if语句)获取String参数并按字母顺序重新排序时遇到麻烦。 The task then requires us to check two phrases against each other to check if the phrases are anagrams. 然后,该任务要求我们彼此检查两个短语,以检查这些短语是否为字谜。 The loop is the bit I am stuck with. 循环是我所坚持的。 My for loop should output the first phrase in alphabetical order, but my if statement is not functioning as intended. 我的for循环应按字母顺序输出第一个短语,但是我的if语句未按预期运行。 The boolean statement is incorrect but I am unsure what I should be checking the phrase.charAt(i) against to record the letter. 布尔语句是不正确的,但是我不确定我应该对那个短语.charAt(i)进行检查以记录该字母。

We are not permitted to use an array to complete this task. 我们不允许使用数组来完成此任务。

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

我认为问题是,你是用内循环的指数比较, i ,要与外环的指标,比较alphabet

if (phrase.charAt(i) == alphabet)

change condition in if statement to if (phrase.charAt(i) == alphabet) 将if语句中的条件更改为if (phrase.charAt(i) == alphabet)

or you can use below function to check two string anagram 或者您可以使用以下功能检查两个字符串字谜

boolean checkAnagram(String st1, String st2)
{   int arr[]=new int[26];
    int l1=st1.length();
    int l2=st2.length();
    if(l1!=l2){
        return false;
    }
for(int i=0;i<l1;i++){
    arr[st1.charAt(i)-97]+=1;
    arr[st2.charAt(i)-97]-=1;
}
 for(int i=0;i<25;i++){
     if(arr[i]!=0) return false;
 }
    return true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM