I am trying to matching total number of records but not able to do it because my one totalcount strong in list type variable and another is getting store in single integer variable.
My Code :
`Base.getdriver().get(Js_constants.DashboardURL);
List<WebElement> totaljobs = Base.getdriver().findElements(By.className(Js_constants.TopsJobsactualtotal));
System.out.println(totaljobs.size()); //OUTPUT 30
//Integer.parseInt(totaljobs); //THIS IS NOT WORKING..WHY?
String Topjobscount = Base.getdriver().findElement(By.xpath(Js_constants.Topsjobscount)).getText();
System.out.println(Topjobscount); //OUTPUT 30
Integer.parseInt(Topjobscount);
//HERE IT IS NOT SUPPORTING CONDITION LIKE THIS.
if(Topjobscount == (totaljobs.size()))
{
System.out.println("Jobs & Count are matching");
Reporter.log("Jobs & Count are matching");
}
else
{
System.out.println("Jobs & Count are matching");
Reporter.log("Jobs & Count are not matching");
}
}`
I am using selenium webdriver & Java. I want to compare both variable count but issue is it does not allow me to convert list type variable to integer.
Topjobscount varibale is a string and you are trying to compare it with an int value.
Calling Integer.parseInt(Topjobscount) wont convert your string to int.You have to assign the value returned by Integer.parseInt(Topjobscount) to an int value and then compare.
Try this.
int x = Integer.parseInt(Topjobscount);
if(x == (totaljobs.size()))
Remember to catch NumberFormatException
Integer.parseInt() documentation states that
Returns:
the integer value represented by the argument in decimal.
Throws:
NumberFormatException - if the string does not contain a parsable integer.
So you need to save that returned value into Integer variable and use that variable.
int count = Integer.parseInt(Topjobscount);
if(count == (totaljobs.size()))
Java is strictly a types language. That means following.
You can not supply anything into a method, it has to be strictly in the same object hierarchy. It results a compile time error if trying to supply wrong type of value as a parameter.
E.g. in your code List<WebElement> totaljobs clearly says type of object totaljobs is List.
Where in Integer.parseInt() takes a parameter type of String. So you can not supply a List type of value where string is expected.
rather you can pass size of list by converting it in string as shown following.
String.valueOf(totaljobs.size());
will return a string representation of size of the list.
However you can convert this string value back to integer by calling Integer.parseInt(String.valueOf(totaljobs.size()));
But above does not make any sense as size() method of List, returns an integer value.
Topjobscount is a String value which can not be compared to int value without converting it to integer.
So you can correct (Topjobscount == (totaljobs.size())) by converting String into integer. As given below.
if (Integer.parseInt(Topjobscount) == totaljobs.size())
Hope this helps.
Related
Can an int be null in Java?
For example:
int data = check(Node root);
if ( data == null ) {
// do something
} else {
// do something
}
My goal is to write a function which returns an int. Said int is stored in the height of a node, and if the node is not present, it will be null, and I'll need to check that.
I am doing this for homework but this specific part is not part of the homework, it just helps me get through what I am doing.
Thanks for the comments, but it seems very few people have actually read what's under the code, I was asking how else I can accomplish this goal; it was easy to figure out that it doesn't work.
int can't be null, but Integer can. You need to be careful when unboxing null Integers since this can cause a lot of confusion and head scratching!
e.g. this:
int a = object.getA(); // getA returns a null Integer
will give you a NullPointerException, despite object not being null!
To follow up on your question, if you want to indicate the absence of a value, I would investigate java.util.Optional<Integer>
No. Only object references can be null, not primitives.
A great way to find out:
public static void main(String args[]) {
int i = null;
}
Try to compile.
In Java, int is a primitive type and it is not considered an object. Only objects can have a null value. So the answer to your question is no, it can't be null. But it's not that simple, because there are objects that represent most primitive types.
The class Integer represents an int value, but it can hold a null value. Depending on your check method, you could be returning an int or an Integer.
This behavior is different from some more purely object oriented languages like Ruby, where even "primitive" things like ints are considered objects.
Along with all above answer i would like to add this point too.
For primitive types,we have fixed memory size i.e for int we have 4 bytes and char we have 2 bytes. And null is used only for objects because there memory size is not fixed.
So by default we have,
int a=0;
and not
int a=null;
Same with other primitive types and hence null is only used for objects and not for primitive types.
The code won't even compile. Only an fullworthy Object can be null, like Integer. Here's a basic example to show when you can test for null:
Integer data = check(Node root);
if ( data == null ) {
// do something
} else {
// do something
}
On the other hand, if check() is declared to return int, it can never be null and the whole if-else block is then superfluous.
int data = check(Node root);
// do something
Autoboxing problems doesn't apply here as well when check() is declared to return int. If it had returned Integer, then you may risk NullPointerException when assigning it to an int instead of Integer. Assigning it as an Integer and using the if-else block would then indeed have been mandatory.
To learn more about autoboxing, check this Sun guide.
instead of declaring as int i declare it as Integer i then we can do i=null;
Integer i;
i=null;
Integer object would be best. If you must use primitives you can use a value that does not exist in your use case. Negative height does not exist for people, so
public int getHeight(String name){
if(map.containsKey(name)){
return map.get(name);
}else{
return -1;
}
}
No, but int[] can be.
int[] hayhay = null; //: allowed (int[] is reference type)
int hayno = null; //: error (int is primitive type)
//: Message: incompatible types:
//: <null> cannot be converted to int
As #Glen mentioned in a comment, you basically have two ways around this:
use an "out of bound" value. For instance, if "data" can never be negative in normal use, return a negative value to indicate it's invalid.
Use an Integer. Just make sure the "check" method returns an Integer, and you assign it to an Integer not an int. Because if an "int" gets involved along the way, the automatic boxing and unboxing can cause problems.
Check for null in your check() method and return an invalid value such as -1 or zero if null. Then the check would be for that value rather than passing the null along. This would be a normal thing to do in old time 'C'.
Any Primitive data type like int,boolean, or float etc can't store the null(lateral),since java has provided Wrapper class for storing the same like int to Integer,boolean to Boolean.
Eg: Integer i=null;
An int is not null, it may be 0 if not initialized. If you want an integer to be able to be null, you need to use Integer instead of int . primitives don't have null value. default have for an int is 0.
Data Type / Default Value (for fields)
int ------------------ 0
long ---------------- 0L
float ---------------- 0.0f
double ------------- 0.0d
char --------------- '\u0000'
String --------------- null
boolean ------------ false
Since you ask for another way to accomplish your goal, I suggest you use a wrapper class:
new Integer(null);
I'm no expert, but I do believe that the null equivalent for an int is 0.
For example, if you make an int[], each slot contains 0 as opposed to null, unless you set it to something else.
In some situations, this may be of use.
i am very very new to Java and i would like to know how can i compare 2 integers? I know == gets the job done.. but what about equals? Can this compare 2 integers? (when i say integers i mean "int" not "Integer").
My code is:
import java.lang.*;
import java.util.Scanner;
//i read 2 integers the first_int and second_int
//Code above
if(first_int.equals(second_int)){
//do smth
}
//Other Code
but for some reason this does not work.. i mean the Netbeans gives me an error: "int cannot be dereferenced" Why?
int is a primitive. You can use the wrapper Integer like
Integer first_int = 1;
Integer second_int = 1;
if(first_int.equals(second_int)){ // <-- Integer is a wrapper.
or you can compare by value (since it is a primitive type) like
int first_int = 1;
int second_int = 1;
if(first_int == second_int){ // <-- int is a primitive.
JLS-4.1. The Kinds of Types and Values says (in part)
There are two kinds of types in the Java programming language: primitive types (§4.2) and reference types (§4.3). There are, correspondingly, two kinds of data values that can be stored in variables, passed as arguments, returned by methods, and operated on: primitive values (§4.2) and reference values (§4.3).
If you want to compare between
1-two integer
If(5==5)
2- char
If('m'=='M')
3 string
String word="word"
word.equals("word")
int is primitive type.This itself having value but Integer is object and it is having primitive int type inside to hold the value.
You can do more operations like compare,longValue,..more by Using wrapper Integer.
== for Integer will not work the rang above -128 and 127. Integer hold cache value upto this range only in memory. More than this range you have to equals() method only to check Integer wrapper class.
equals() method will check the value stored in the reference location.
As int is primitive you can not use equals.
What you can do
Use Interger as wrapper
void IntEquals(Integer original, Integer reverse) {
Integer origianlNumber = original;
Integer reverseNumber = reverse;
if (origianlNumber.equals(reverse)) {
System.out.println("Equals ");
} else {
System.out.println("Not Equal");
}
I have an Integer value of variable as below:
Integer programNumber= ........
I took the program number as Integer type. However in my other class, I want to check whether this variable, programNumber, equals variable which is the type of int.
To sum up, I want to convert the variable of the of Integer to int primitive value.
I used programno.intValue() but it doesn't work.
Thanks in advance.
I have a two class, BasvuruKisi and Program. the code snippet is below:
BasvuruKisi bsvkisi = (BasvuruKisi) (this.getHibernateTemplate().find("from BasvuruKisi bsv where bsv.basvuruNo=?", basvuruNumaralari.get(i))).get(0);
if (bsvkisi != null) {
int yetkiVarmi = 0;
Integer programno= bsvkisi.getProgramId();
List array =
this.getHibernateTemplate().find("from Program p where p.id=?", programno.intValue());
but
this.getHibernateTemplate().find("from Program p where p.id=?", programno.intValue());
this one doesn't work. return firstly, no table or view is available despite available and then returns null pointer exception.
thanks
The variable name in the initialization block says programNumber, but the variable in the method call is programno. Which is it?
Using the wrong variable name shouldn't give you a null pointer exception, unless you have another variable named programno defined somewhere.
Whatever the variable name is, make sure you initialize it before you get the intValue.
Validate programNumber is null or not?
If the value is null, it throws Exception.
Integer programNumber= null;
System.out.println(programNumber.intValue());
I have received the following error message
G:\CIS260\Assignments>javac PhoneNumber.java
PhoneNumber.java:45: error: incompatible types
number = decode(c);
^
required: int
found: String
1 error
in the beginning of the class i have
char c;
private int number = 0
This makes it an int so i understand that in order for the next line to compile i have to have two of the same data types. My understanding is that
str[1].valueOf(number);
number = decode(c);
public static String decode(char c){
switch (c) {
should make the variable NUMBER a string making decode and number equal data types because they are both strings.
I feel like i may be forgetting a step in order to make both strings data types. any thoughts?
char c = 0; //is not declared and initalized
number = Integer.parseInt(decode(c));
yes you are declaring number as Integer.
so you should cast it by using Integer.ParseInt.
You have the method public static String decode(char c) which returns a value of String, but the variable number accepts the value String which is declared as an Integer
Try having a return type of Integer like public static int decode(char c)
Your method returns a String.
You are trying to store that returned string in an int.
Java does not convert strings to integers automatically like this. You will have to do the conversion explicitly. You can use Integer.parseInt for this:
int number = Integer.parseInt(decode(c));
Note that a NumberFormatException will be thrown if the returned string isn't actually a valid integer.
I need a way to return the type of an object (as a string, or class of the object, whichever is easier) given a string with the value in it.
I could parse it with each of the types I want, but there are problems associated with that (such as an int may also be parsed as a long, a float can be parsed as a double). Here's my sketch:
private String typeOf(String test) {
if (test == "true" || test == "false")
return "boolean";
else if (// its a number)
// figure out a way to parse all number types?
// return corresponding type
else
// can't be parsed with any boolean or number types... just a string
return "string";
}
The types I am checking are: String, long, int, short, byte, byte[], float, and double.
Remember I need the SPECIFIC type in order to accomplish the make-or-break functionality of this program. Any help is appreciated.
I'm trying to make a Named Binary Tag (specifications here) that holds a specific type of data given by user input (a JOptionPane - input dialog). In order to make the correct type of tag, I need to know the type of the data given. (Is there a way to get the input from the user where I can avoid the String problem entirely?) Having a String to work with in the first place has become the main source of my issue.
To start your String checking is incorrect. Aside from that think about the different datatypes and their possible values.
An int or Integer's possibles values all lie within the ranges of a long. The same is true for Floats and Doubles. You will need to figure out which Datatype's ranges are subsets of which and test in that order. As an example here is a quick snippit for testing for Integers and Longs.
private String typeOf(String suppliedTest) {
String test = suppliedTest.strip().toLower();
if (test.equals("true") || test.equals("false"))
return "boolean";
try {
int testInt = Integer.parseInt(test);
return "integer";
} catch (NumberFormatException e) {}
try {
long testLong = Long.parseLong(test);
return "long";
catch (NumberFormatException e) {}
...
}
You can use class specific parsing methods to check, if a String represents a certain type, such as
Double.parseDouble()
Integer.parseInt()
these methods will throw NumberFormatException if the input string does not contain a value, that represents the appropriate type.
You don't have enough different to know the difference. All you can do is find the smallest type when can represent that data. a 0 could be a String, long, int, short, byte, float or double. You will need to decide which would be the most appropriate response.