class Test {
public static void main(String[] args) {
long[] longarr = {40, 50, 70, 90};
int sum = 0;
for (int x: (int) longarr) {
sum += x;
}
System.out.println("sum is " + sum);
}
}
how could we fix the error without making the long type array to int. is there any way to do so?
You have a couple of problems with your code:
long[]
to an int[]
like this --> (int) longarr
, so what you need to do is leave it as for (int x: longarr) {...}
for (int x: longarr) {...}
a new error arises as the compiler cannot explicitly cast a long
to an int
therefore you can change the type of the variable to for (long x: longarr) {...}
long
to an int
before applying the summation. This is what @Meini's approach does, but here is another approach anyway:
int summation = Arrays.stream(longarr).mapToInt(v -> (int)v).sum();
Note that mapToInt
is required here to actually get the int
value you require otherwise if we were to assign directly the summation of long
s to an int
variable the compiler will complain as a long
can store much larger values than an int
.
another version:
int summation = (int)Arrays.stream(longarr).sum();
Try
public static void main(String[] args) {
long[] longarr = {40, 50, 70, 90};
int sum = 0;
for (long x : longarr) {
sum += (int) x;
}
System.out.println("sum is " + sum);
}
Actually you don't have to explicitly cast x
to int
-> sum += x;
, i leave it there to make it more clearly
Your question was must be :
how to fix error : incompatible types: long cannot be converted int
Change in the loop to :
public class NewClass {
public static void main(String[] args) {
long[] longarr = {40, 50, 70, 90};
int sum = 0 ;
for (long x: longarr ) { // don't need cast
sum += x;
}
System.out.println("sum is " + sum);
}
}
run:
sum is 250
Correct :
for (long x : longarr) {
}
No need to do an explicit type cast.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.