+ 2

Why does this code give me an error code because of possibly lossy conversion and this one doesnt?

This one works: import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int amount = scanner.nextInt(); //your code goes here int x = 0; int newAmount = amount; while (x < 3){ newAmount = newAmount - newAmount / 10; x++; } System.out.println(newAmount); } } But this one doesnt: import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int amount = scanner.nextInt(); //your code goes here int x = 0; int newAmount = amount; while (x < 3){ newAmount = newAmount - newAmount * 0.1; x++; } System.out.println(newAmount); } }

28th Jul 2021, 3:48 PM
ShadowSwat GTV
ShadowSwat GTV - avatar
3 Answers
+ 8
By multiplying with 0.1 the result becomes double. However, newAmount is defined as integer. Therefore the error.
28th Jul 2021, 4:01 PM
Lisa
Lisa - avatar
+ 3
At first glance, looks to be because you're using a double in the second one when it's of int type. Just convert it and it should work fine.
28th Jul 2021, 3:57 PM
Jakko Jak
Jakko Jak - avatar
+ 2
https://code.sololearn.com/ca1135a15A8a import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int amount = scanner.nextInt(); //your code goes here int x = 0; double newAmount = amount; while (x < 3){ newAmount = newAmount - newAmount * 0.1; x++; } System.out.println(newAmount); } }
28th Jul 2021, 3:58 PM
Jakko Jak
Jakko Jak - avatar