Wrong why explain please | Sololearn: Learn to code for FREE!


Wrong why explain please

import java.util.Scanner; public class Javac { public static void main(String[] args) { Scanner sc= new Scanner(System.in); int num=sc.nextInt(); System.out.print(convert(num)); } public static int convert(int num) { int dec=0; int i=0; while(num>0) { int temp=num%10; // dec+=(temp*Math.pow(2, i)); num=num/10; i++; } return dec; } } // if i write like this //dec=dec+(temp*Math.pow(2, i)); //why is not work //

4/21/2021 10:39:20 AM

Sachin Saxena

3 Answers

New Answer


To answer your original question. When you use the syntax dec = dec + (temp * Math.pow(2, i)); The Java compiler throws the error... Javac.java:15: error: incompatible types: possible lossy conversion from double to int dec = dec + (temp * Math.pow(2, i)); ^ 1 error This because the result of using Math.pow() is a double thus the result of the calculation is a double, which you are attempting to assign to an int (dec). When you use the syntax... dec += (temp * Math.pow(2, i)); the entire expression is being assigned to an int so the compiler appears to automatically cast the result. To achieve the same thing explicitly use dec = dec + (int)(temp * Math.pow(2, i)); Though I'm not sure what you are trying to do here both versions of the code return the same values for the same input. I made the assumption on seeing pow(2, i) that you were trying to convert it to binary (base 2) but that is not what the code is doing.


It is working fine. In terms of syntax


If this is supposed to be your solution for the Binary Converter problem in the Java Course you are way off the mark. The class is supposed to called Converter not Javac. Note also that javac is the name of the java compiler. The toBinary method is supposed to return a string. import java.util.Scanner; class Converter { static String toBinary(int n){ return Integer.toBinaryString(n); } } public class Program { public static void main(String[ ] args) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); System.out.print(Converter.toBinary(x)); } } It isn't actually necessary to create a class to do this since Java has built in methods to do this in most of the Numeric classes. It's purely an exercise in writing a class and a method. In other words... import java.util.Scanner; public class Program { public static void main(String[ ] args) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); System.out.print(Integer.toBinaryString(x)); } } is all that is required usually.