gpt4 book ai didi

java - 我正在尝试检查 Anagram

转载 作者:行者123 更新时间:2023-12-02 01:05:46 27 4
gpt4 key购买 nike

为什么代码向我显示缺少 return 语句的错误?

我想做的是检查字符串的长度及其内容并比较它们。

import java.util.Scanner;

public class Solution {
static boolean isAnagram(String a, String b) {
char[] arr1 = a.toLowerCase().toCharArray();
char[] arr2 = b.toLowerCase().toCharArray();
java.util.Arrays.sort(arr1);
java.util.Arrays.sort(arr2);
if (arr1.length != arr2.length) {
if (!arr1.equals(arr2)) {
System.out.println("Not Anagrams");
}
return false;
} else if (arr1.equals(arr2)) {
System.out.println("Anagrams");
return true;
}
}

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String a = scan.next();
String b = scan.next();
scan.close();
boolean ret = isAnagram(a, b);
System.out.println((ret) ? "Anagrams" : "Not Anagrams");
}
}

最佳答案

主要问题

You need to have a "return" outside if statements.

else if(arr1.equals(arr2))
{
System.out.println("Anagrams");
return true;
}

return false; //add this here. I tested, error goes after this.
}

在这里测试 - https://onlinegdb.com/S188-FdGL

额外

Your Anagram logic is wrong.

The correct logic should be like this (follow comments to understand).

import java.util.Scanner;
import java.util.Arrays;

public class Solution {

static boolean isAnagram(String a, String b)
{
char[] arr1 = a.toLowerCase().toCharArray();
char[] arr2 = b.toLowerCase().toCharArray();

int n1 = arr1.length;
int n2 = arr2.length;

// If length is different, then they cannot be Anagram
if (n1 != n2) return false;

// Sort the Character Arrays
Arrays.sort(arr1);
Arrays.sort(arr2);

// Compare each characters of sorted Character Arrays,
// if any character mismatches, it is not an Anagram
for (int i = 0; i < n1; i++)
if (arr1[i] != arr2[i])
return false;

// If all characters of both character Arrays are same,
// only then, the String are Anagrams, so return true
return true;

// Also, remove the print statements from this method,
// as you are already printing in the main method,
// so it creates duplicate prints
}


public static void main(String[] args) {

Scanner scan = new Scanner(System.in);
String a = scan.next();
String b = scan.next();
scan.close();

boolean ret = isAnagram(a, b);
System.out.println( (ret) ? "Anagrams" : "Not Anagrams" );
}
}

在这里测试 - https://onlinegdb.com/rJe-OEtuGL

关于java - 我正在尝试检查 Anagram,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60080135/

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