This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am a beginner in Java. I need to compare two arrays of string and find out if any value from the first array matches any value in second array?
Here is my function which does not work as expected,
public static boolean CheckStatAppearinLeftAndRight1(String[] array1, String[] array2)
{
boolean b = false;
for (int i = 0; i < array2.length; i++)
{
for (int a = 0; a < array1.length; a++)
{
if (array2[i] == array1[a])
{
b = true;
break;
}
else
{
b = false;
}
}
}
return b;
}
Can someone please point out the issue here?
if (array2[i] == array1[a])
should be
if ((array2[i]).equals(array1[a]))
try>>>
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws Exception {
int[] ary = {1,2,3,4,5,6};
int[] ary1 = {1,2,3,4,5,6};
int[] ary2 = {1,2,3,4};
System.out.println("Is array 1 equal to array 2?? "
+Arrays.equals(ary, ary1));
System.out.println("Is array 1 equal to array 3?? "
+Arrays.equals(ary, ary2));
}
}
Use array2[i].equals(array1[i]) instead of using == operator.
== operator compares the two references and would give you false.
equals() method is already overriden in class String which matches the exact characters from two different String Objects.
boolean b = false;
for (int i = 0; i < array2.length; i++)
{
for (int a = 0; a < array1.length; a++)
{
if (array2[i].equals(array1[a]))
{
b = true;
break;
}
else
{
b = false;
}
}
if(b)
return b;
}
}
Related
This question already has answers here:
equals vs Arrays.equals in Java
(9 answers)
Closed 1 year ago.
I am trying to check if a number is palindrome or not, I took the numbers in a string then put them into an array of numbers, and I was able to reverse this array of numbers into a new array. Now I want to check if numbersL[]==numbersLreversed[]. Note that my equal here means that both arrays got the same elements at the same indices.
import java.util.*;
public class Array_and_its_reverse {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String numberS = in.next(); //12121
String numbersarrayed[] = numberS.split(""); // put numbers in a string array
long numbersL[] = new long[numbersarrayed.length]; // original
for (int i = 0; i < numbersarrayed.length; i++) {
numbersL[i] = Long.parseLong(numbersarrayed[i]);
System.out.println(numbersL[i]);
}
long numbersLreversed[] = new long[numbersarrayed.length];
System.out.println("Array in reverse order: ");
for (int i = numbersL.length - 1; i >= 0; i--) {
numbersLreversed[i] = numbersL[i];
System.out.println(numbersLreversed[i]);
}
if (numbersLreversed == numbersL) {
System.out.println("right");
} else {
System.out.println("NO");
}
}
}
== checks for identity (i.e., both operands are the exact same object reference), which, as you see, won't be appropriate here. Instead, you can use the JDK's Arrays.equals:
if (Arrays.equals(numbersLreversed, numbersL)) {
System.out.println("right");
} else {
System.out.println("NO");
}
This question already has answers here:
determine if string has unique characters
(11 answers)
Closed 1 year ago.
I want my code to return true if all the characters in the string are different but it returns true even if some of the characters are the same .For example in the string input the character 'r' is repeated three times and the method still returns true.What am I doing wrong?
My code:
public static void main(String[]args)
{
System.out.println(code("qrrrtyuioplkjhgfdsazxcvbnm")); }
public static boolean code(String input)
{
for (int i = 0; i < 27; i++)
{
char temp=input.charAt(i);
char x =input.charAt(i+1);
if(temp!=x)
{
return true;
}
}
return false;
}
Running through each line of the code, we can see that it is checking the two characters next to each other. The first two characters are "qr", since these are different the function returns true, and doesn't even look at the three r's in a row. For it to achieve what you asked in the question the code should look like this:
public static void main(String[] args) {
System.out.println(code("qrrrtyuioplkjhgfdsazxcvbnm"));
}
public static boolean code(String input) {
for (int i = 0; i < input.length(); i++) { //I have changed it from 27, to input.length() as I assume you want it to work for any input
for (int j = i+1; j < input.length(); j++) {
if(input[i] == input[j]) {
return false;
}
}
}
return true;
}
public static boolean code(String input)
{
if (input.length > (26 or 52)) //depending if the string have upper case char or not, if you are do not know which char could be there just put the max number of char or delete the line with return state
return false;//if you have more than that number of character you for sure will have repetition due to pigeon hole principle
for (int i = 0; i < input.length; i++)
for (int j = i + 1; j < input.length; j++)
{
if (input.charAt(i) == input.charAt(j)) //check for all pairs to not to be the same
return false; //if found at least one pair of identical
}
return true;//if nothing found return true
}
Use a Set and return false as soon as something is present in the set, otherwise return true after cycling through the input string..
public boolean checkUniqueLetters(String inputString) {
Set<String> letterSet = new HashSet<>();
for (String letter : inputString.split("")) {
if (letterSet.contains(letter)) {
return false;
} else {
letterSet.add(letter);
}
}
return true;
}
https://docs.oracle.com/javase/8/docs/api/java/util/Set.html
I am creating a method compareTo(AltString altStr2) that sorts strings by their length (shortest to longest).
However, I would like to go the extra mile and check for strings that are of the same length. In that case, I figure it is best to sort the strings lexicographically, so that they are sorted in the same way they would appear in the dictionary. So far my code is below.
public class AltString {
String internalStr;
public AltString(String str) {
internalStr = str;
}
public String toString() {
return internalStr;
}
public int compareTo(AltString altStr2) {
if (this.internalStr.length() < altStr2.internalStr.length()) {
return -1;
} else if (this.internalStr.length() > altStr2.internalStr.length()) {
return 1;
} else {
int idx = 0;
while (this.internalStr.charAt(idx) != altStr2.internalStr.charAt(idx)) {
if (this.internalStr.charAt(idx) < altStr2.internalStr.charAt(idx)) {
return -1;
}else if (this.internalStr.charAt(idx) > altStr2.internalStr.charAt(idx)) {
return 1;
} else {
idx += 1;
public static void main(String[] args) {
// some test code for the AltString class
String [] list = {"fortran", "java", "perl", "python", "php", "javascrip", "c", "c++", "c#", "ruby"};
AltString [] alist = new AltString[list.length];
for (int i=0; i<alist.length; i++) {
alist[i] = new AltString(list[i]);
}
Arrays.sort(list);
Arrays.sort(alist);
System.out.println("String sort:");
for (int i=0; i<list.length; i++) {
System.out.println(list[i]);
}
System.out.println("\nAltString sort:");
for (int i=0; i<alist.length; i++) {
System.out.println(alist[i]);
}
}
The part I am must stuck on is comparing the strings lexicographically. Currently, I have my code setup so that I enter a while-loop and compare each char.
My question is, is this the most efficient way to do this, or is there a better way to compare each string lexicographically in the cases where the strings are the same length?
Following the suggestions of Tunaki and JB Nizet, you can use Integer.compare and String.compareTo. Using String.compareTo does not count as recursion. Recursion is when you call a method from itself, but String.compareTo is a different method from AltString.compareTo.
public int compareTo(AltString altStr2) {
int temp = Integer.compare(this.internalStr.length(), altStr2.internalStr.length());
return temp != 0 ? temp : this.internalStr.compareTo(altStr2.internalStr);
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
Im trying to make a simple programm that compares if a number or word is a palindrome. Ive made the following code, but I dont get why my if statement doesnt work. If you print the results you can see the numbers or letters are the same but my if statement doesnt think so. Here is my code. Thanks :
import java.util.*;
public class myPalindromo
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
String number;
ArrayList < String > myNumber = new ArrayList < String > ();
Scanner sn = new Scanner(System.in);
number= sn.nextLine();
for(int i = 0 ; i<number.length() ; i++)
{
myNumber.add(number.valueOf(number.charAt(i)));
}
for(int i = 0; i<myNumber.size(); i++)
{
System.out.println(myNumber.get(i)+"=="+myNumber.get((myNumber.size()-1)-i));
if(myNumber.get(i)== myNumber.get((myNumber.size()-1)-i))
System.out.println("palindrome");
else
System.out.println("not palindrome");
}
}
}
To check if a string is palindrome try this:
static boolean isPalindrome(String s) {
int center = (int)s.length()/2 - 1;
for (int i = 0; i <= center; i++) {
if (s.charAt(i) != s.charAt(s.length() - i-1) )
return false;
}
return true;
}
You should change the If statement to this one
if(Integer.parseInt(myNumber.get(i))== Integer.parseInt(myNumber.get((myNumber.size()-1)-i)))
Thats because you were comparing string instead of the actual numbers.
You can use the reverse method in the StringBuilder to accomplish this.
public static boolean isPalindrome(String str) {
return str.equals(new StringBuilder(str).reverse().toString());
}
I'm trying to find if two string are anagrams of each other:
void anagram(String a, String b) {
List<Character> bcopy = new ArrayList<Character>();
for (int i = 0; i < b.length(); i++)
bcopy.add(b.charAt(i));
if (b.length() == 0 || a.length() == 0) {
System.out.println("Exit");
} else {
for (int i = 0; i < a.length(); i++) {
char temp = a.charAt(i);
if (bcopy.contains(temp)) {
System.out.println("match found" + temp);
bcopy.remove(temp);
}
for (char j : bcopy) {
System.out.println("Values" + j);
}
}
}
}
I keep getting an out of bounds error at the remove() line. Can someone please tell me how I reach the array bounds when I'm searching by the object availability? What am I missing here?
The problem is you're using the int-argument version of remove() since the char temp is being treated as an int. Here's a workaround:
bcopy.remove(Character.valueOf(temp));
By the way a better way to test for anagrams would be something like:
char[] c1 = a.toCharArray();
char[] c2 = b.toCharArray();
Arrays.sort(c1);
Arrays.sort(c2);
return Arrays.equals(c1, c2); // true -> anagram, false -> not anagram
there is another algorithm which might be more suitable to the task. it computes the letter frequencies for strings of equal lengths.
for simplicity i assume that the set of all characters involved can be represented in one of the common 8 bit codepages.
void anagram(String a, String b) {
int freqa[256], freqb[256];
if (b.length() == 0 || a.length() == 0) {
System.out.println("Exit");
return;
}
for (int i = 0; i < b.length(); i++) {
freqa[(int) a.charAt(i)]++;
freqb[(int) b.charAt(i)]++;
}
for (i = 0; i < 256; i++) {
if (freqa[i] <> freqb[i]) {
System.out.println("Exit");
return;
}
}
System.out.println("match found: '" + a + "', '" + b + "'");
}
There is a problem with your code. You are removing the items from a list however the loop is running 'n' times is the string length is 'n'.
So if item is removed from the list and the loop count reaches a number which Index is removed from list it will give the exception. You can keep a count instead of removing the items. I modified your code little bit which is working fine now.
Please check
import java.util.ArrayList;
import java.util.List;
class Anagram{
void anagram(String a, String b) {
List<Character> bcopy = new ArrayList<Character>();
int count=0;
for (int i = 0; i < b.length(); i++)
bcopy.add(b.charAt(i));
if (b.length() == 0 || a.length() != b.length()) {
System.out.println("Two strings are not anagram");
} else {
for (int i = 0; i < a.length(); i++) {
char temp = a.charAt(i);
if (bcopy.contains(temp)) {
//System.out.println("match found" + temp);
//bcopy.remove(temp);-- Here list size was reduced but the loop was constant, because list size is less than a.length() now it was giving error
//System.out.println(c);
count++;
}
}
if(count==a.length()) {
System.out.println("Two strings are anagram");
}
else {
System.out.println("Two strings are not anagram");
}
}
}
}
public class Test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Anagram a=new Anagram();
a.anagram("abs", "ass");
}
}