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.
Related
String bob2 = "3";
System.out.println((int)bob2);
I'm unsure of why this causes an exception. Can anyone explain? Pretty sure because of the int on String type, but want to make sure.
Yes you are right its because of typecasting. If u need to convert String to int use below code
Integer.parseInt("3");
You are correct.
You can't just cast a string to an int.
You should convert it using Integer.parseInt()
Use this
Integer.valueOf("3");
or
Integer.parseInt("3");
In Java whenever you are trying to change type of an entity to another, both the types should have some relation. Like if you are trying to caste a sub class object to super class, it will work smoothly. But if you try to compare a Person object with a Lion object, that comparison is meaning less, the same is the logic in casting. We cannot cast a Person object to Lion object.
In your code bob is String type and you are trying to cast it to int and in Java both String and Integer is not having any relation. That's why Java is throwing Exception, Class Cast Exception I guess, this is raised when different types of objects are compared.
But the parseInt(String arg) method in Integer class gives an option to convert numeric String to Integer, given that the argument is a qualified Integer as per Java standards.
Example :-
String numericString = "1234";
int numberConverted = Integer.parseInt(numericString);
System.out.println(numberConverted);
You can also try these which will tell you the precautions before using this method
int numberConverted = Integer.parseInt("1234r");
int numberConverted = Integer.parseInt("1234.56");
int numberConverted = Integer.parseInt("11111111111111111111111111111");
You can't cast String to Integer. Change:
System.out.println((int)bob2);
to:
System.out.println(Integer.parseInt(bob2));
It will create an Integer value from the String provided with bob2 variable. You can also create a reference to int variable like this if you want to store primitive int instead of Integer:
int intBob2 = Integer.parseInt(bob2);
This question already has answers here:
How do I convert a String to an int in Java?
(47 answers)
Closed 7 years ago.
public class ArrayManipulations {
public static void main(String[] args) {
String name = num.toString();
System.out.println(name); // want to convert this back to int
System.out.println(num.getClass().getName() + '#' + Integer.toHexString(num.hashCode()));
}
}
Now i want to convert the name back to integer.
is it possible???
Yes.
int i = Integer.parseInt(name);
Yes you can
Return an Object Integer :
Integer var = Integer.valueOf("0");
This method returns the relevant Number Object holding the
value of the argument passed. The argument can be a primitive data
type, String, etc.
Return a primitive int :
int var = Integer.parseInt("0");
This method is used to get the primitive data type of a certain
String. parseXxx() is a static method and can have one argument or
two.
The Integer class provides the following method for this task:
Integer.parseInt(String s);
Yes.
Integer.parseInt(Integer.toString(3));
should do the trick.
More in the Java Documentation.
If you want to convert String to int, you use:
int intNum = Integer.parseInt(name); //name is variable that you want to change back to int
Why does this program return error: incompatible types: int cannot be converted to String ?
public class StringConcatenation{
public static void main(String []args){
int[] testing = {0,1,3,4,5,6};
String mark = "";
for(int i=0;i<testing.length;i++)
{
// mark += testing[i]; But this line works fine
mark = testing[i]; /* This line doesn't work */
}
System.out.println(mark);
}
}
StringConcatenation.java:8: error: incompatible types: int cannot be converted to String
mark = testing[i];
The first way uses string concatenation, which is special cased in the Java language to allow you to use any object or primitive type. However, you cannot just assign a random value to a String.
The + operator can handle a string and an integer, converting the integer to string before concatenating. But you can't assign an integer to a string. Has nothing to do with using an array.
The operation += which translates to addition over its current value, converts integer to string and then concatenates it to the current state of string. However when you try to assign an integer value to a reference which is of type string, compiler will throw an error.
There are languages that will do even this for you, but it just does not work like that in a strongly typed language like java.
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.
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");
}