Why the code is showing me the error for missing return statement?
What I am trying to do is check the length of the string followed by its content and compare both of them.
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");
}
}
PRIMARY QUESTION
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.
}
Tested here - https://onlinegdb.com/S188-FdGL
EXTRA
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" );
}
}
Tested here - https://onlinegdb.com/rJe-OEtuGL
Related
I am trying to write a code the will print TRUE when i enter a word with no vowels and will print FALSE if I enter a word with vowels. I am having trouble when it comes to writing the string. I give one of the strings the value that holds all the values.
String A = "aeiou";
The other 2 strings hold the rest of the alphabet.
When I type in a word that has vocals it prints FALSE however when I type in a word with no vowels it prints FALSE.
I wanna know if there is a way to make the program read the values of the string as separate entities and not as a whole line.
package lab3;
import java.util.Scanner;
public class Lab3 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String input = reader.next();
/* A and B, but not C */
String A = "bcdfghjklm";
String B = "npqrstvwxyz";
String C = "aeiou";
if (input.contains(A) && input.contains(B) || input.contains(C)) {
System.out.println("TRUE");
} else {
System.out.println("FALSE");
}
}
}
You can do it with a short function
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String input = reader.next();
System.out.println(chk(input));
}
static public boolean chk(String s) {
for (int i = 0; i < s.length(); i++) {
if ("aeiou".indexOf(s.charAt(i)) != -1) {
return false;
}
}
return true;
}
}
This is a working correct for your purpose:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String input = reader.next();
String C = "aeiou";
for (int i = 0; i < input.length(); i++) {
char inputA = input.charAt(i);
for (int j = 0; j < C.length(); j++) {
char c = C.charAt(j);
if (inputA == c) {
System.out.println("TRUE");
return;
}
}
}
System.out.println("FALSE");
}
The key point is to use the method charAt(int index); so you can check each char in the string.
You can choose to use any of the below two methods, containsVowel and containsVowel1 as both of them do the same thing:
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a text: ");
String input = reader.nextLine();
String[] vowels = { "a", "e", "i", "o", "u" };
System.out.println(!containsVowel(input, vowels));
System.out.println(!containsVowel1(input, vowels));
}
public static boolean containsVowel(String input, String[] vowels) {
return Arrays.stream(vowels).parallel().anyMatch(input::contains);
}
public static boolean containsVowel1(String input, String[] vowels) {
for (int i = 0; i < vowels.length; i++) {
if (input.contains(vowels[i])) {
return true;
}
}
return false;
}
}
Refer below Java code for palindrome.
This is to check if the code logic is right or wrong
/* Please expalin why this logic is wrong*/
public class IntegerIsPalindrome {
public static boolean numPalindrome(int x){
String ParseNum = Integer.toString(x);
int lenPar = ParseNum.length();
for(int i = 0 ; i < ParseNum.length();i++){
if(ParseNum.charAt(0) != ParseNum.charAt(lenPar -1 -i)){
return false;
}
}
return true;
}
public static void main(String args[]){
boolean result = numPalindrome(323);
System.out.println(result);
}
}
It's because you always compare the first character. Specifically:
ParseNum.charAt(0)...
You should change this to:
ParseNum.charAt(i)...
Looking into 323, the first character, '3', and the last, '3', is compared. Then, the first '3' is compared with the '2', resulting in false.
You should iterate loop upto ParseNum.length()/2 is enough.
Ex: If value is 12321,
you should check
charAt[0] with charAt[4] means 1=1
charAt[1] with charAt[3] means 2=2
for(int i = 0 ; i < ParseNum.length()/2;i++){
if(ParseNum.charAt(i) != ParseNum.charAt(lenPar -1 -i)){
return false;
}
}
you should need to change ParseNum.charAt(0) in the for loop into ParseNum.charAt(i)
Here the code you can find palindrome easily:
package com.company;
import java.util.Scanner;
public class Palindrome
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Input: ");
String input = scanner.next();
System.out.println(isPalindrome(input) ? "palindrome" : "not a palindrome");
}
private static boolean isPalindrome(String input)
{
String temp = "";
for (int i = input.length() - 1; i >= 0; i--)
{
temp += input.charAt(i);
}
return input.equalsIgnoreCase(temp);
}
}
The object is to take a phrase entered by the user and tell them whether it is a palindrome or not. It must have an array and a method. I am having trouble with my array and the return result for my method. I have edited it some but I am still having trouble with the boolean part. No matter what I enter I am getting false. I would also like to make sure that if there was any spaces entered that they would be removed. I have tried the replaceAll but could not get that to work. Thank you for the help.
import java.util.Scanner;
public class palindrome {
public palindrome() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
int another=1;
boolean results;
System.out.println("Please enter a phrase to be checked:");
String input = keyboard.next();
if (checkpalindrome(input))
System.out.println("Yes, the phrase is a palindrome");
else
System.out.println("No, the phrase is not a palindrome");
System.out.println("Would you like to try another one? \"1 or 0\"");
another = keyboard.nextInt();
}
public static boolean checkpalindrome(String input){
char array2 = 0;
char[] array1 = input.toCharArray();
StringBuilder sb = new StringBuilder(input.length());
for(int i=0; i<array1.length/2; i++)
{
array2 = array1[i];
array1[i]=array1[array1.length-1-i];
array1[array1.length-1-i]=array2;
}
System.out.println(input);
System.out.println(array1);
System.out.println(test.equals(array1));
return(input.equals(array1));
}
}
You can use this method also to check if the string is palindrome or not.
public static boolean pallindrom(String S)
{
char arr[] = S.toCharArray();
int flag = 0;
for(int i = 0 ; i < (arr.length+1)/2 ; i++)
{
if(arr[i] != arr[arr.length-1-i])
{
flag = 1;
break;
}
}
if(flag == 0)
return true;
else
return false;
}
Here is the problem statement: Write a function that compares 2 strings to return true or false depending on if both strings contain the same letters. Order doesn't matter.
I do not know how to properly compare the character arrays in my nested for loop. I wish I could be more specific with what my issue is, but I'm a really new learner and can't see why this isn't working. I do believe it's not doing what I would like in the nested for loops. Thanks in advance!
import java.util.Scanner;
public class PracticeProblems {
public static boolean stringCompare(String word1, String word2) {
char[] word1b = new char[word1.length()];
char[] word2b = new char[word2.length()];
boolean compareBool = false;
for(int i = 0; i < word1.length(); i++) {
word1b[i] = word1.charAt(i);
word2b[i] = word2.charAt(i);
}
for(int i = 0; i < word1.length(); i++) {
for(int j = 0; j < word2.length(); j++) {
if(word1b[i] == word2b[j]) {
compareBool = true;
break;
} else {
compareBool = false;
break;
}
}
}
return compareBool;
}
public static void main(String []args) {
Scanner scan = new Scanner(System.in);
System.out.println("Word 1?");
String word1 = scan.nextLine();
System.out.println("Word 2?");
String word2 = scan.nextLine();
if(PracticeProblems.stringCompare(word1, word2) == true) {
System.out.println("Same Letters!");
} else {
System.out.println("Different Letters...");
}
}
The code below will do the job. This is essentially an expansion of Frank's comment above. We convert the two strings to two sets and then compare.
import java.util.*;
public class SameChars {
// Logic to convert the string to a set
public static Set<Character> stringToCharSet(String str) {
Set<Character> charSet = new HashSet<Character>();
char arrayChar[] = str.toCharArray();
for (char aChar : arrayChar) {
charSet.add(aChar);
}
return charSet;
}
// Compares the two sets
public static boolean hasSameChars(String str1, String str2) {
return stringToCharSet(str1).equals(stringToCharSet(str2));
}
public static void main(String args[]){
// Should return true
System.out.println(hasSameChars("hello", "olleh"));
// Should returns false
System.out.println(hasSameChars("hellox", "olleh"));
}
}
I sorted arrays before comparing.
//import statement for Arrays class
import java.util.Arrays;
import java.util.Scanner;
public class PracticeProblems {
public static boolean stringCompare(String word1, String word2) {
char[] word1b = new char[word1.length()];
char[] word2b = new char[word2.length()];
boolean compareBool = true;
for(int i = 0; i < word1.length(); i++) {
word1b[i] = word1.charAt(i);
}
//sort the new char array
Arrays.sort(word1b);
// added a second loop to for the second world
for(int i = 0; i < word2.length(); i++) {
word2b[i] = word2.charAt(i);
}
Arrays.sort(word2b);
for(int i = 0; i < word1.length(); i++) {
//removed second for loop.
// for(int j = 0; j < word2.length(); j++) {
// if the two strings have different length, then they are different
if((word1.length()!=word2.length())){
compareBool = false;
break;
}
//changed to not equal
if( (word1b[i] != word2b[i]) ) {
compareBool = false;
break;
}
//removed else statment
// else {
// compareBool = false;
// break;
//
// }
}
return compareBool;
}
public static void main(String []args) {
Scanner scan = new Scanner(System.in);
System.out.println("Word 1?");
String word1 = scan.nextLine();
System.out.println("Word 2?");
String word2 = scan.nextLine();
if(PracticeProblems.stringCompare(word1, word2) == true) {
System.out.println("Same Letters!");
} else {
System.out.println("Different Letters...");
}
//resource leak. use close() method.
scan.close();
}
}
Allow me to rename your boolean variable to letterFound (or maybe even letterFoundInWord2) because this is what you are checking in your double loop. Explanatory naming makes it easier to keep the thoughts clear.
Since you are checking one letter from word1 at a time, you can move the declaration of letterFound inside the outer for loop and initialize it to false here since each time you take a new letter from word1 you haven’t found it in word2 yet. In your if statement inside the for loops, it is correct to break in the case the letters are the same and you set letterFound to true. In the opposite case, don’t break, just go on to check the next letter. In fact you can delete the else part completely.
After the inner for loop, if letterFound is still not true, we know that the letter from word1 is not in word2. So stringCompare() should return false:
if (! letterFound) {
return false;
}
With this change, after the outer for loop we know that all letters from word1 were found in word2, so you can type return true; here.
Except:
You seem to be assuming the strings have the same length. If they have not, you program will not work correctly.
As Andy Turner said, you should also check that all the letters in word2 are in word1; it doesn’t follow from the letters from word1 being in word2.
Should only letters be considered? Should you ignore spaces, digits, punctuation, …?
Hope you will be able to figure it out. Feel free to follow up in comments or ask a new question.
I am solving this question as an assignment of the school. But the two of my test cases are coming out wrong when I submit the code? I don't know what went wrong. I have checked various other test cases and corner cases and it all coming out right.
Here is my code:
public static boolean isPermutation(String input1, String input2) {
if(input1.length() != input2.length())
{
return false;
}
int index1 =0;
int index2 =0;
int count=0;
while(index2<input2.length())
{
while(index1<input1.length())
{
if( input1.charAt(index1)==input2.charAt(index2) )
{
index1=0;
count++;
break;
}
index1++;
}
index2++;
}
if(count==input1.length())
{
return true;
}
return false;
}
SAMPLE INPUT
abcde
baedc
output
true
SAMPLE INPUT
abc
cbd
output
false
A simpler solution would be to sort the characters in both strings and compare those character arrays.
String.toCharArray() returns an array of characters from a String
Arrays.sort(char \[\]) to sort a character array
Arrays.equals(char \[\], char \[\]) to compare the arrays
Example
public static void main(String[] args) {
System.out.println(isPermutation("hello", "olleh"));
System.out.println(isPermutation("hell", "leh"));
System.out.println(isPermutation("world", "wdolr"));
}
private static boolean isPermutation(String a, String b) {
char [] aArray = a.toCharArray();
char [] bArray = b.toCharArray();
Arrays.sort(aArray);
Arrays.sort(bArray);
return Arrays.equals(aArray, bArray);
}
A more long-winded solution without sorting would to be check every character in A is also in B
private static boolean isPermutation(String a, String b) {
char[] aArray = a.toCharArray();
char[] bArray = b.toCharArray();
if (a.length() != b.length()) {
return false;
}
int found = 0;
for (int i = 0; i < aArray.length; i++) {
char eachA = aArray[i];
// check each character in A is found in B
for (int k = 0; k < bArray.length; k++) {
if (eachA == bArray[k]) {
found++;
bArray[k] = '\uFFFF'; // clear so we don't find again
break;
}
}
}
return found == a.length();
}
You have two ways to proceed
Sort both strings and then compare both strings
Count the characters in string and then match.
Follow the tutorial here
In case you String is ASCII you may use the next approach:
Create 256 elements int array
Increment element of corresponding character whenever it's found in string1
Decrement element of corresponding character whenever it's found in string2
If all elements are 0, then string2 is permutation of string1
Overall complexity of this approach is O(n). The only drawback is space allocation for charCount array:
public static boolean isPermutation(String s1, String s2) {
if (s1.length() != s2.length()) {
return false;
}
int[] charCount = new int[256];
for (int i = 0; i < s1.length(); i++) {
charCount[s1.charAt(i)]++;
charCount[s2.charAt(i)]--;
}
for (int i = 0; i < charCount.length; i++) {
if (charCount[i] != 0) {
return false;
}
}
return true;
}
If your strings can hold non-ASCII values, the same approach could be implemented using HashMap<String, Integer> as character count storage
I have a recursive method to solve the permutations problem. I think that this code will seem to be tough but if you will try to understand it you will see the beauty of this code. Recursion is always hard to understand but good to use! This method returns all the permutations of the entered String 's' and keeps storing them in the array 'arr[]'. The value of 't' initially is blank "" .
import java.io.*;
class permute_compare2str
{
static String[] arr= new String [1200];
static int p=0;
void permutation(String s,String t)
{
if (s.length()==0)
{
arr[p++]=t;
return;
}
for(int i=0;i<s.length();i++)
permutation(s.substring(0,i)+s.substring(i+1),t+s.charAt(i));
}
public static void main(String kr[])throws IOException
{
int flag = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the first String:");
String str1 = br.readLine();
System.out.println("Enter the second String:");
String str2 = br.readLine();
new permute_compare2str().permutation(str1,"");
for(int i = 0; i < p; ++i)
{
if(arr[i].equals(str2))
{
flag = 1;
break;
}
}
if(flag == 1)
System.out.println("True");
else
{
System.out.println("False");
return;
}
}
}
One limitation that I can see is that the length of the array is fixed and so will not be able to return values for a large String value 's'. Please alter the same as per the requirements. There are other solution to this problem as well.
I have shared this code because you can actually use this to get the permutations of a string printed directly without the array as well.
HERE:
void permutations(String s,String t)
{
if (s.length()==0)
{
System.out.print(t+" ");
return;
}
for(int i=0;i<s.length();i++)
permutations(s.substring(0,i)+s.substring(i+1),t+s.charAt(i));
}
Value of 's' is the string whose permutations is needed and value of 't' is again empty "".
it will take O(n log n) cuz i sort each string and i used more space to store each one
public static boolean checkPermutation(String a,String b){
return sortString(a).equals(sortString(b));
}
private static String sortString(String test) {
char[] tempChar = test.toCharArray();
Arrays.sort(tempChar);
return new String(tempChar);
}
String checkPermutation(String a,String b){
char[] aArr = a.toCharArray();
char[] bArr = b.toCharArray();
Arrays.sort(aArr);
Arrays.sort(bArr);
if(aArr.length != bArr.length){
return "NO";
}
int p = 0, q = 0;
while(p < aArr.length){
if(aArr[p] != bArr[q]){
return "NO";
}
p++;
q++;
}
return "YES";
}
public static boolean isStringArePermutate(String s1, String s2){
if(s1==null || s2==null) {
return false;
}
int len1 = s1.length();
int len2 =s2.length();
if(len1!=len2){
return false;
}
for(int i =0;i<len1;i++){
if(!s1.contains(String.valueOf(s2.charAt(i)))) {
return false;
}
s1=s1.replaceFirst(String.valueOf(s2.charAt(i)), "");
}
if(s1.equals("")) {
return true;
}
return false;
}