Java 错误:不兼容的类型可能导致从浮点到字符的有损转换
我在这个项目上工作了一个小时,仍然找不到解决办法。我总是遇到同样的错误(EnigmaEncrypt.java:44:error:不兼容的类型:从float到char的可能有损转换) char e=示例charinput; ^ 1个错误) 这是我的密码:Java 错误:不兼容的类型可能导致从浮点到字符的有损转换,java,Java,我在这个项目上工作了一个小时,仍然找不到解决办法。我总是遇到同样的错误(EnigmaEncrypt.java:44:error:不兼容的类型:从float到char的可能有损转换) char e=示例charinput; ^ 1个错误) 这是我的密码: import java.util.Scanner; // Created by ab38 on 2015-12-01. public class EnigmaEncrypt { // Static Scanner field
import java.util.Scanner;
// Created by ab38 on 2015-12-01.
public class EnigmaEncrypt {
// Static Scanner field
private static Scanner scan;
/**
* Get a char from the command line.
*
* @return the first char of the current line, typed by the user
* on the command line.
*/
private static char getChar() {
return scan.next().charAt(0);
}
/**
* Get an integer from the command line.
*
* @return the integer on the current line, typed by the user
* on the command line.
*/
private static int getInt() {
return scan.nextInt();
}
public static void main(String[] args) {
scan = new Scanner(System.in);
// Example: How to get an integer from the command line:
System.out.println("Enter an integer:");
int exampleIntInput = getInt();
System.out.println("Rotorposition: " + exampleIntInput);
// Example: How to get a single char from the command line:
System.out.println("Enter a single character:");
float exampleCharInput = getChar() + exampleIntInput;
char e = exampleCharInput;
System.out.println("Char from command line: " + e);
}
}
char以2字节存储,float以4字节存储。你试图在不进行施法的情况下将一个浮点数放入一个字符中。试试这个
char e = (char) exampleCharInput;
char以2字节存储,float以4字节存储。你试图在不进行施法的情况下将一个浮点数放入一个字符中。试试这个
char e = (char) exampleCharInput;
“我还是找不到解决办法”:你想解决哪个问题?我想这与加密有关,但请详细说明。另外,你给一个字符分配了一个浮点数——为什么?这个字符意味着什么?你把一个int和一个字符的和赋给了一个float——为什么?这个总和意味着什么?当你把
char
加到int
上时,结果就是int
。然后尝试将其分配给字符
。这是一种“可能的有损转换”,因为对于表达式的某些值,赋值将从值的高端“切掉”重要位。“我仍然找不到解决方案”:您试图解决哪个问题?我想这与加密有关,但请详细说明。另外,你给一个字符分配了一个浮点数——为什么?这个字符意味着什么?你把一个int和一个字符的和赋给了一个float——为什么?这个总和意味着什么?当你把char
加到int
上时,结果就是int
。然后尝试将其分配给字符
。这是一种“可能有损转换”,因为对于表达式的某些值,赋值将从值的高端“切掉”有效位。