'Error: incompatible types: possible lossy conversion from double to in [duplicate]
I'm trying to print the start value with the conversion but I'm getting this error:
error: incompatible types: possible lossy conversion from double to int
int zeile = Programm.printTable(10.0, 1000.0, 50);
This is my code
public class miles {
public static double km2meilen(double entfernung) {
return (entfernung / 1.852);
}
public static double meilen2km(double entfernung) {
return ((double) entfernung * 1.852);
}
public static double printTable(double start, double end, double step) {
System.out.printf("\n km Seemeilen Seemeilen km");
double y = 0.0;
for (; start <= end; start += end) {
double x = 0.0;
System.out.printf("\n%10.2f %10.2f %10.2f %10.2f", (double) start, (double) km2meilen(start), (double) start, (double) meilen2km(start));
x = x + 1.0;
return x;
}
}
public static void main(String[] args) {
printTable(0.0, 50.0, 1000.0);
}
}
Solution 1:[1]
The printTable
method returns a double
so you may save it in a double, or explicitly cast it
double zeile = Programm.printTable(10.0, 1000.0, 50);
int zeile = (int) Programm.printTable(10.0, 1000.0, 50);
Then, your conversion methods don't need any cast
public static double km2meilen(double entfernung) {
return entfernung / 1.852;
}
public static double meilen2km(double entfernung) {
return entfernung * 1.852;
}
And your printTable
doesn't define x
where it should, and doesn't return it where it should, and has useless casting too
public static double printTable(double start, double end, double step) {
System.out.printf("\n%10s %10s %10s %10s", "km", "Seemeilen", "Seemeilen", "km");
double y = 0.0;
double x = 0.0;
for (; start <= end; start += step) {
System.out.printf("\n%10.2f %10.2f %10.2f %10.2f", start, km2meilen(start), start, meilen2km(start));
x = x + 1.0;
}
return x;
}
km Seemeilen Seemeilen km
10,00 5,40 10,00 18,52
60,00 32,40 60,00 111,12
110,00 59,40 110,00 203,72
160,00 86,39 160,00 296,32
210,00 113,39 210,00 388,92
260,00 140,39 260,00 481,52
310,00 167,39 310,00 574,12
360,00 194,38 360,00 666,72
410,00 221,38 410,00 759,32
460,00 248,38 460,00 851,92
510,00 275,38 510,00 944,52
560,00 302,38 560,00 1037,12
610,00 329,37 610,00 1129,72
660,00 356,37 660,00 1222,32
710,00 383,37 710,00 1314,92
760,00 410,37 760,00 1407,52
810,00 437,37 810,00 1500,12
860,00 464,36 860,00 1592,72
910,00 491,36 910,00 1685,32
960,00 518,36 960,00 1777,92
Solution 2:[2]
Conversion might be issue, you can type case it as mentioned below , moreover, printTable
is giving compilation error, you might need to put return
outside of for loop.
int zeile = (int)Programm.printTable(10.0, 1000.0, 50);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |