为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

长风秋雁 2021-08-25 16:40:51
我正在为大学做另一项编码任务。我在使用 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));    }}
查看完整描述

2 回答

?
慕丝7291255

TA贡献1859条经验 获得超6个赞

将 if 语句中的条件更改为 if (phrase.charAt(i) == alphabet)


或者您可以使用以下函数来检查两个字符串字谜


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;

}


查看完整回答
反对 回复 2021-08-25
?
ITMISS

TA贡献1871条经验 获得超8个赞

我认为问题在于您正在与内循环i的索引 进行比较,您想与外循环的索引 进行比较alphabet

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


查看完整回答
反对 回复 2021-08-25
  • 2 回答
  • 0 关注
  • 186 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信