Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从long到int的可能有损转换,can';找不到错误_Java_Compiler Errors - Fatal编程技术网

Java 从long到int的可能有损转换,can';找不到错误

Java 从long到int的可能有损转换,can';找不到错误,java,compiler-errors,Java,Compiler Errors,在这段代码中,我不断得到: error: incompatible types: possible lossy conversion from long to int rem = num%16; 1 error 这是我目前正在使用的代码 public class BaseConverter{ public static String convertToBinary(long num){ long binary[] = new long[40]; int

在这段代码中,我不断得到:

 error: incompatible types: possible lossy conversion from long to int
        rem = num%16; 
 1 error
这是我目前正在使用的代码

public class BaseConverter{

public static String convertToBinary(long num){
    long binary[] = new long[40];
    int index = 0;
    while(num > 0){
        binary[index++] = num%2;
        num = num/2;
    }
    for(int i = index-1; i>= 0;i--){
        System.out.print(binary[i]);
    }
}
public static String convertToHexadecimal(long num){
    int rem;

    // For storing result
    String str=""; 

    // Digits in hexadecimal number system
    char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

    while(num>0)
    {
        rem = num%16; 
        str = hex[rem]+str; 
        num = num/16;
    }
}
}

基本上,这段代码应该帮助我设置另一个调用静态方法的程序。但是由于这个错误,我无法编译。

您的问题在第行
rem=num%16
将类型为
long
的值分配给类型为
int
的变量

一般规则是,应用其中一个算术运算符的结果是所操作的两种类型中较大的一种。用这个人的话来说 ,

乘法表达式的类型是其操作数的提升类型

因此,表达式
num%16
具有类型
long
,因为
num
具有类型
long
;即使其值始终在-15和15之间。将
long
表达式指定给
int
变量而不显式强制转换它是错误的

你可以写

rem = (int) num % 16;

避免此错误。

是,因为此代码

 rem = num%16; 
rem是int类型,num是long,您需要添加类型转换

rem = (int)num%16;
还要为这两种方法添加返回语句以成功编译。

使用以下方法:

rem = (int) (num % 16);
别忘了你的回报声明:

return str;

编写
返回long.toBinaryString(num)的过程非常漫长
返回Long.toHexString(num)好的,成功了!但是现在我得到了这个错误:BaseConverter.java:13:error:missing return statement}^BaseConverter.java:30:error:missing return statement}^2个错误。这是因为两个方法中都缺少
return
语句。您已经在每个方法的顶部说过,它们返回一个
字符串
。您需要让它们返回
字符串
,或者将每个声明中的
字符串
更改为
无效
。例如,添加
返回strconvertToHexadecimal
方法底部的code>可能就是您所需要的;为了工作,我会在第一个方法中添加什么?好的,你现在已经证明了你知道你需要知道的一切,以便在没有我进一步输入的情况下解决这些问题。祝你好运