Java compare char on string array - java

Imagine I have a String array like this:
String[][] fruits = {{"Orange","1"}, {"Apple","2"}, {"Arancia","3"};
If I do this:
for (int i = 0; i < fruits.length;i++){
System.out.println(fruits[i][0].charAt(1));
}
it will print:
r
p
r
And if I do this:
for (int i = 0; i < fruits.length;i++){
Character compare = fruits[i][0].charAt(1);
System.out.println(compare.equals('r'));
}
it will print:
true
false
true
So here is my question. Is it possible to use charAt and equals on the same line, I mean, something like this:
System.out.println((fruits[i][0].charAt(1)).equals("r"));
Regards,
favolas

Yes, provided you convert the result of charAt() to Character first:
System.out.println(Character.valueOf(fruits[i][0].charAt(1)).equals('r'));
A simpler version is to write
System.out.println(fruits[i][0].charAt(1) == 'r');
I personally would always prefer the latter to the former.
The reason your version doesn't work is that charAt() returns char (as opposed to Character), and char, being a primitive type, has no equals() method.
Another error in your code is the use of double quotes in equals("r"). Sadly, this one would compile and could lead to a painful debugging session. With the char-based version above this would be caught at compile time.

Certainly! Try this:
System.out.println((fruits[i][0].charAt(1)) == 'r');
We're doing a primitive comparison (char to char) so we can use == instead of .equals(). Note that this is case sensitive.
Another option would be to explicitly cast the char to a String before using .equals()
If you're using a modern version of Java, you could also use the enhanced for syntax for cleaner code, like so:
public static void main(String[] args) {
String[][] fruits = {{"Orange","1"}, {"Apple","2"}, {"Arancia","3"}};
for (String[] fruit: fruits){
System.out.println((fruit[0].charAt(1)) == 'r');
}
}

The char data type, which is returned from String.charAt() is a primitive, not an object. So you can just use the == operator to perform the comparison as it will compare the value, not the reference.
System.out.println((fruits[i][0].charAt(1) == 'r'));

Related

Java Compare two ArrayList<Integer> [duplicate]

int [] nir1 = new int [2];
nir1[1] = 1;
nir1[0] = 0;
int [] nir2 = new int [2];
nir2[1] = 1;
nir2[0] = 0;
boolean t = nir1.equals(nir2);
boolean m = nir1.toString().equals(nir2.toString());
Why are both m and t false? What is the correct way to compare 2 arrays in Java?
Use Arrays.equals method. Example:
boolean b = Arrays.equals(nir1, nir2); //prints true in this case
The reason t returns false is because arrays use the methods available to an Object. Since this is using Object#equals(), it returns false because nir1 and nir2 are not the same object.
In the case of m, the same idea holds. Object#toString() prints out an object identifier. In my case when I printed them out and checked them, the result was
nir1 = [I#3e25a5
nir2 = [I#19821f
Which are, of course, not the same.
CoolBeans is correct; use the static Arrays.equals() method to compare them.
Use Arrays.equals instead of array1.equals(array2). Arrays.equals(array1, array2) will check the content of the two arrays and the later will check the reference. array1.equals(array2) simply means array1 == array2 which is not true in this case.
public static boolean perm (String s, String t){
if (s.length() != t.length()) {
return false;
}
char[] perm1 = s.toCharArray();
Arrays.sort(perm1);
char[] perm2 = t.toCharArray();
Arrays.sort(perm2);
return Arrays.equals(perm1, perm2);
}
boolean t = Arrays.equals(nir1,nir2)
I just wanted to point out the reason this is failing:
arrays are not Objects, they are primitive types.
When you print nir1.toString(), you get a java identifier of nir1 in textual form. Since nir1 and nir2 were allocated seperately, they are unique and this will produce different values for toString().
The two arrays are also not equal for the same reason. They are separate variables, even if they have the same content.
Like suggested by other posters, the way to go is by using the Arrays class:
Arrays.toString(nir1);
and
Arrays.deepToString(nir1);
for complex arrays.
Also, for equality:
Arrays.equals(nir1,nir2);
Use this:
return Arrays.equals(perm1, perm2)
Instead of this:
return perm1.equals(perm2);
Please have to look this

why cant we use <, <=, >,>= relational operators on String?

I want to know why we cant use the <, <=, > or >= relational operators on Strings.
import java.util.*;
public class Coffee{
public static void main(String args[]){
String s1="Cat";
String s2="Dog";
System.out.println(s1 < s2);
}
}
gives the error "operator < cannot be applied to java.lang.String".
Why can't Java compare strings like this: C < D?
The simple answer is: because they weren't implemented. Java (unlike e.g. C/C++) does not rely on operator overloading, so you have to get the value of a String with length method and then compare the results with your < > <= >= operators.
Side note: Strings in Java also implement Comparable interface. It allows you to use compareTo method, which returns 0 if the argument is a strings are equal, a value less than 0 if the argument is greater than string which you run this method on; and a value greater than 0 if the argument is a string smaller than this string.
Side note 2: By "greater string" I mean lexicographically greater (alphabetically).
String is not a primitive data type like int and double are. Strings are objects.
For Strings, the relational operator, ==, only checks to see if the objects "point" to the same data in the heap.
For example,
String s1="Cat";
String s2= new String("Cat");
if(s1==s2)
System.out.println("They are the same");
The if statement WILL NOT execute.
This is because after you created an instance of "Cat", you create another instance of "Cat," in the heap. The two variables do not "point" to the same data.
compareTo methods check to see if the actual data that the variables are allocated to in a heap are equal to each other, and is one of the many correct ways to see if two String objects are equal to each other.
I hope it helped, if my response is unclear, please do not hesitate to ask.
If you really want to do this, use the compareTo result.
if ("a".compareTo("b") >= 0) {
// do stuff
}
If you want to ignore case you can do:
if (String.CASE_INSENSITIVE_ORDER.compare("A", "b") <= 0) {
// do stuff
}
Here's the right way:
import java.util.*;
public class Coffee {
public static void main(String args[]) {
String s1="Cat";
String s2="Dog";
System.out.println(s1.compareTo(s2));
}
}

How i can control whether a char[] is null?

I wrote this code to control whether a char[] is null or not.
char[] xxx = new char[9];
for (int i = 0; i < 9; ++i)
{
if (xxx[i]==null)
{
xxx[i]=i;
}
}
Each element of a char[] is a char, which is a primitive type. Primitive types cannot be null, so your comparison will never return true. If you say more about what you are trying to accomplish, you may get some useful advice about how to do it.
What is char[] in your example? if _board is a char[] then you are checking if one of the char is null, chars can't be null since char is a primitive type.
I'm guessing you should do
if (_board == null)
if (xxx[i]==0)
this code works.0 means that in char is null.try it.
You are using the word "control" in a confusing way.
Your code will test if _board[i] is null. It is correct in that sense. It might fail if
_board was not defined.
i was not defined.
_board is not an array
_board is not an array of objects (only object references can be null)
It will "work" but not "do anything" if _board[i] is not null.

Java code snippet logic

I cannot see what I am doing wrong here. Here is the code I am having trouble with :
String tempSummaryString = "SUMMARY:";
for(int z = 0; z<attributeList.size() ; z++)
{
System.out.println(attributeList.get(z).substring(0,tempSummaryString.length()));
if(attributeList.get(z).length() > tempSummaryString.length() &&
attributeList.get(z).substring(0,tempSummaryString.length() == tempSummaryString)
{
event.setTitle(attributeList.get(z).substring(tempSummaryString.length(),attributeList.get(z).length()));
}
}
Now my problem is that the program never goes into the if (does not execute the event.setTitle method). When I print the value of
attributeList.get(z).substring(0,tempSummaryString.length())
I get the following:
SUMMARY:
So I am stumped about why it is not entering the if! I don't get it!
Hopefully someone can point out a stupid mistake I am making because I really dont know what else to do
You've fallen for the old == vs equals() problem. You are using ==, which unlike javascript, does an identity comparison (ie are these the same objects).
Try this:
attributeList.get(z).substring(0,tempSummaryString.length())
.equals(tempSummaryString) // equals() not ==
Also, you should consider using the foreach syntax for your loop:
for (String attribute : attributeList) {
if (attribute.substring... // forget about attributeList.get(z) and even z
}
Don't compare strings using the == operator (as in attributeList.get(z).substring(0,tempSummaryString.length()) == tempSummaryString), use the String.Equals method instead.
Your problem is this: attributeList.get(z).substring(0,tempSummaryString.length())== tempSummaryString. You compare references, not string contents. Use String.equals(otherString) to that end.
You should compare the Strings with equals().
attributeList.get(z).substring(0,tempSummaryString.length()).equals(tempSummaryString)
You're comparing strings with ==, while you should use the String class' .equals() method.

What causes the "Incompatible operand types" error?

I am trying to implement iSortableStack Interface via a class.
Here's my main function,
public class SampleStack<E> {
E ch;
#SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException {
ISortableStack<Character> s = new SortableStack<Character>();
SampleStack demo = new SampleStack();
while ((demo.ch == System.in.read()) != '\n')
if (!s.isFull())
s.push((Character) demo.ch);
while (!s.isEmpty())
System.out.print(s.pop());
System.out.println();
}
}
But I am getting one error, on this line,
while ((demo.ch == System.in.read()) != '\n')
Error : Incompatible operand types Object and int
What is wrong here ?
There are two severe problems here that have nothing to do with generics.
First, demo.ch == System.in.read() is a boolean expression. The result of read() (an int) will be auto-boxed to an Integer, and the identity of that object will be tested against demo.ch (which is null).
I think that what you want here is the assignment operator, =. This will assign the read() result to demo.ch.
The next problem is that it looks like you expect demo.ch to be a Character (based on the casts you are using). However, you are trying to assign an int (the result of read()) to it. Primitive types can be "auto-boxed" when necessary, that is, they can be converted to a wrapper object like Character or Integer, but only when the value to be converted is a constant expression that can be represented by the target type. Here, the value is variable, so the conversion cannot be performed implicitly.
You could work around this by explicitly casting the read() result to a char, and then letting the auto-boxing convert it to a Character, but that would hide EOF, which is represented by a value of -1. I recommend using something like this instead:
while (true) {
int ch = System.in.read();
if ((ch < 0) || (ch == '\n'))
break;
if (!s.isFull())
s.push((char) ch);
}
Note that we don't use demo here at all, so the problems with its type parameter are irrelevant.
SampleStack.ch is of type E. E is an object specified by your type parameters. Since you did not specify a type parameter, the compiler puts Object in for you. If you wanted ch to be a Character, you would want SampleStack<Character> demo = new SampleStack<Character>(); or in Java 7 SampleStack<Character> demo = new SampleStack<>();.
You haven't provided a type parameter when you instantiate SampleStack, so demo.ch is of type Object. That obviously can't be compared (or assigned, which is what I suspect you actually wanted to do, anyway) from the int coming from System.in.
You have == (equality test) when you want = (assignment). You're never actually assigning to demo.ch. The equality test returns boolean, rather than char, hence the error message.
You will also need to cast the result from System.in.read() to a character from an integer (or else use SampleStack<Integer>, or something like that.)
You have several errors in this code:
as people pointed out you're making a generic class but you're not generalizing it and using it raw, you need:
SampleStack<Character>
even if you change it it wont run as you have == instead of =
even if you change the above two it wont work as System.in.read() returns an int, not a character, You'd need to either make a stack of Integers OR read the value from the input to a variable and then cast it but its not a good practice. I'd use a Scanner or somethign similar to read what the user inputs like this:
Scanner sc = new Scanner(System.in);
char c = sc.nextChar();

Categories

Resources