Why can i not cast this string as an int? [duplicate] - java

This question already has answers here:
How do I convert a String to an int in Java?
(47 answers)
Closed 7 years ago.
I'm having problems when taking a value out of a list and then casting it as an integer so I then can use it for different math functions, such as multiplication.
Current code :
int i = 0;
while(i < student_id.size()){
String finding = student_id.get(i).toString();
int s101 = ((Integer)score101.get(student101.indexOf(finding))); // <----this is where im having problems
System.out.println(student_id.get(i)+" "+names.get(i));
System.out.println("IR101 " +
score101.get(student101.indexOf(finding)) +
" IR102 " +
score102.get(student102.indexOf(finding)));
i++;
}
The error that im getting is java.lang.String cannot be cast to java.lang.Integer. This confuses me because I thought it would have been an object. I have tried to convert it to an integer from both an object and a String but both throw up errors. How can I convert score101.get(student101.indexOf(finding)) to an int ?

The error is pretty clear, java.lang.String cannot be cast to java.lang.integer.
That means score101.get(student101.indexOf(finding)) return a String. If the string represent an Integer then you can parse it easily
Integer.parseInt(score101.get(student101.indexOf(finding)))
Edit
As per your comment, the string is a Double so you need to use parseDouble
Double.parseDouble(score101.get(student101.indexOf(finding)))
If you really want it as an int and discard the decimal, you can call intValue() which will cast it to an int (or cast directly).
Double.parseDouble(score101.get(student101.indexOf(finding))).intValue()

You can parse string with Integer.parseInt(String s) method

Related

Cast double to int, but only if exact conversion [duplicate]

This question already has answers here:
How to test if a double is an integer
(18 answers)
Closed 3 years ago.
I'm getting a value of type double from an API which, in my specific case, should always return a whole number in a range well within int's — any non-whole number will mean something went very wrong inside that API call. I do want to know when this happens.
I know I can do a post-conversion check like, let say:
double value = …;
int whole_number = (int) value;
if(value != whole_number) throw …;
Is there any shorter idiom to "Convert a double to int only if it is an exact conversion, and raise an exception if not"?
Your solution seems simplest to me. You can do it as a one-liner:
if (value != (int)value)) throw ...
but if you want the exception to be thrown for you, the only thing I can think of is to go through a String, which seems really convoluted, especially since you can't just use String.valueOf(value) to get the string:
// Seems really convoluted
Integer.parseInt(new DecimalFormat("##.###").format(d));
You can use the following check if needed
if (value % 1 != 0) {
throw...
}
Using an Optional<Double> you could use the following logic
Integer result = Optional.of(value)
.filter(d -> d % 1 == 0)
.filter(this::isInRange)
.map(Integer::parseInt)
.orElseThrow(...);
You can use BigDecimal::intValueExact():
int wholeNumber = BigDecimal.valueOf(value).intValueExact();
It will automatically throw an exception: if it has a nonzero fractional part or it is outside the range of int

Why doesn't java store large value in long datatype directly but allows to store it indirectly (without using literals)? [duplicate]

This question already has answers here:
Initialize a long in Java
(4 answers)
The literal xyz of type int is out of range
(5 answers)
Why, In Java arithmetic, overflow or underflow will never throw an Exception?
(4 answers)
Closed 4 years ago.
Here are my 2 examples:
1. Directly assigned value to long data type:
long a = 12243221112432;
I get an error:
integer number too large
But when assisgned like this:
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(12);
al.add(24);
al.add(32);
al.add(21);
al.add(11);
al.add(24);
al.add(32);
long a=0;
for(int i=0; i<al.size(); i++){
a = a*100 + al.get(i);
}
System.out.println(a);
I get this output:
12243221112432
Why doesn't java throw an error in second example?
It isn't allowing to assign large value directly(example 1) but indirectly(example 2) it stores it and also allows me to use it too!
What is the reason for this to occur?
Is it because i am using integer in arraylist or something else?
UPDATE
Why is the large value stored in 'long a' in second example without using literal L?
It should have given me an error during 5th or 6th iteration of for loop...
Note
My question is not regarding the first example... I am asking why it worked for the second example...
Dont mark the question duplicate, since the other questions do not have my answer..stated above
For your assignment to work, you need to write it that way
long a = 12243221112432L;
This will indicate the compiler that your input is a long, not an int
integer number too large
as the error said, the number 12243221112432 is too large for an integer, it does not says that this number cannot fit into a long
Te be able to have this number, you have to make it a long by using the l or L indice : 12243221112432L
long : l L : 1716L
float : f F : 3.69F
double : d D : 6936D

Why am I am getting an incompatible types error? [duplicate]

This question already has answers here:
Promotion in Java?
(5 answers)
Closed 6 years ago.
I'm learning java and creating some simple test programs with notes in them and I'm getting an error saying "incompatible types: possible lossy conversion from int to short" with short shortVal= val5 + val6; I'm looked and this error meaning I'm trying to put an int value into a short variable but the value I'm storing in the short is only 27, so I'm a bit confused as to what is wrong.
public class test{
public static void main(String[] args){
double val1=4;
float val2=9;
long val3=30;
int val4= 8;
short val5= 15;
short val6=12;
byte val7=20;
short shortVal= val5 + val6; //why the error here?
}
}
The result of short + short is, somewhat paradoxically, int. So you're trying to assign an int to a short variable (shortVal).
short + short will result in an int. You need an int variable to store the result :
int shortVal = val5 + val6;

Casting in wrapper classes [duplicate]

This question already has answers here:
Double is not converting to an int
(4 answers)
Closed 8 years ago.
int k=(int)10.0;
Integer j = (Integer ) 10.0;//compile time error
In the second line of code i am getting incompatible types error.my question is why it is not possible to cast wrapper classes in java?As i am able to cast primitives in java.
incompatible types: double cannot be converted to Integer
Integer j = (Integer ) 10.0;
no, you cannot cast primitives to the wrong wrapper class, use int k = Double.valueOf(10.0).intValue() instead or int k=(int)10.0; Integer i = k;

Convert a string value into an int [duplicate]

This question already has answers here:
How do I convert a String to an int in Java?
(47 answers)
How to do an Integer.parseInt() for a decimal number?
(10 answers)
Closed 9 years ago.
How to convert string value into int? I am getting number format exception.
String s = "20.00";
int i = (Integer.parseInt(s));
System.out.println(i);
Result should be like i=20.
What about:
int i = (int) Double.parseDouble(s);
Of course, "20.00" is not in a valid integer format.
String s = "20.00";
is not valid Integer value that is the reason its throwing NumberFormatException.
Format your number using either Double or Float then using narrow casting cast you number to int but you may loose precision if exists.
i.e. int I = (int) Double.parseDouble(str);

Categories

Resources