How to compare between elements of two arrays? [duplicate] - java

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

Related

checking if arraylist is sorted or not [duplicate]

This question already has answers here:
Simple way to find if two different lists contain exactly the same elements?
(20 answers)
Closed 11 months ago.
I need to check if the elements in the arraylist are arranged in ascending order or not. and when i use this code, the output shows "not sorted" even for a sorted array. why is it showing the wrong output?**
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> array1 = new ArrayList<>();
ArrayList<Integer> array2 = new ArrayList<>();
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
array1.add(i, sc.nextInt());
array2.add(i, array1.get(i));
}
Collections.sort(array1);
if (array1 == array2) {
System.out.println("sorted");
}
else {
System.out.println("not sorted");
}
}
"==" checks weather two object identical that means it check weather they point to the same memory location. If your array1 is on #698 location your array2 will be somewhere else like #700 ,so they don't point to the same location that's why it shows they are not equal. You better check it on this way:
if (array1.equals(array2)){
System.out.println("They are equal");
} else{
System.out.println("They are not equal");
Then it shows the right answer
The error using == instead of equals is clear. For arrays there is Arrays.equals(int[] lhs, int[] rhs).
However sort does too much work, and needs a copy of the array.
Better:
static boolean isSorted(List<Integer> list) {
for (int i = 1; i < list.size(); ++i) {
if (list.get(i).compareTo(list.get(i - 1)) < 0) {
return false;
}
}
return true;
}
Could even be more general:
static <T extends Comparable<T>> boolean isSorted(List<T> list) {

Code to build all possible strings, and find a specific one doesen't work as expected [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
Part of a task I'm trying to solve is building all possible combinations of letters and whitespace. I'm trying to find a specific String, while building the combinations. I think i implemented the solution well, but my test tells me otherwise.
I'm taking the chars from an array and in a for loop I build a String from them, then print the solution. When I built all the combinations of let's say "1 character combinations", then i move on to "2 character combinations". I have a boolean to check if the contents of the StringBuilder is equal to the given String that i want to find. I checked, and the example String was indeed built, but the boolean didn't change.
public static void main(String[] args) throws InterruptedException {
findString("rxc");
}
public static void findString(String string) {
boolean isFound = false;
String allChars = "abcdefghijklmnopqrstuvwxyz ";
char[] sequence = allChars.toCharArray();
int lengthOfExpression = 3;
//builder contains 3 whitespaces at the beginning
StringBuilder builder = new StringBuilder(" ");
int[] pos = new int[lengthOfExpression];
int total = (int) Math.pow(allChars.length(), lengthOfExpression);
for (int i = 0; i < total; i++) {
for (int x = 0; x < lengthOfExpression; x++) {
if (pos[x] == sequence.length) {
pos[x] = 0;
if (x + 1 < lengthOfExpression) {
pos[x + 1]++;
}
}
builder.setCharAt(x, sequence[pos[x]]);
}
pos[0]++;
if (builder.toString() == string) {
isFound = true;
}
System.out.println(builder.toString());
}
System.out.println(isFound);
}
Expected result would be a 'true' printed at the end. Instead, my result is as follows:
//lots of lines of combinations omitted
r
s
t
u
v
w
x
y
z
false
Do not compare strings with ==, use .equals() instead; so for your code:
Change the if (builder.toString() == string) to if (builder.toString().equals(string))

How do I prompt a user for a name and remove that name in the array? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
Even though the name I entered is in the array, this piece of code always says it's not on the list. Does it have to do with what I set searchValue equaled to?
String[] stuName = new String[MAX_ON_LIST];
int currentSize = 0;
for (int i = 0; i < stuName.length; i++) {
stuName[i] = JOptionPane.showInputDialog("Enter student name:");
}
String searchValue = JOptionPane.showInputDialog("Enter a name:");;
int position = 0;
boolean found = false;
while (position < stuName.length && !found) {
if (stuName[position] == searchValue) {
found = true;
}
else {
++position;
}
}
if (found) {
stuName[1] = stuName[currentSize - 1];
--currentSize;
JOptionPane.showMessageDialog(null, Arrays.toString(stuName));
}
else {
JOptionPane.showMessageDialog(null, "Name not on list");
JOptionPane.showMessageDialog(null, Arrays.toString(stuName));
}
You should change your
if (stuName[position] == searchValue)
to
if (stuName[position].equalsIgnoreCase( searchValue ) )
The reason is that otherwise you would be comparing objects, and two object are always different even if they contain the same value. Strange but true ;-)
equalsIgnoreCase ensures that you compare the String objects content. You might want to have a look here for more details.
But there is another problem in your code:
if (found) {
stuName[1] = stuName[currentSize - 1];
--currentSize;
This will try to overwrite the second element (array count starts at 0) with element -1 (currentSize equals 0, 0-1 is -1). This will certainly crash with an IndexOutOfBounds exception.
== is used to compare primitive data type values and object references. To compare string values, use
stuName[position].equals(searchValue)

check if palindrome not working [duplicate]

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

Comparing two arrays of Strings [duplicate]

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

Categories

Resources