[英]Inputting String and Convert to ASCII
My problem is that when i input "b" it converts correctly but when i input other letters it just displaying the conversion of "b" 我的问题是,当我输入“ b”时,它可以正确转换,但是当我输入其他字母时,它仅显示“ b”的转换
char ch = 'b';
int ascii = ch;
int castAscii = (int) ch;
DisplayText.setText(UserInput.getText() + " = " + castAscii);
This is because you only convert the character b
to it's ascii value and not the actual user input. 这是因为您仅将字符
b
转换为它的ascii值,而不转换为实际的用户输入。 Assuming that UserInput.getText()
returns the user defined character as character and not string: 假设
UserInput.getText()
返回用户定义的字符为character而不是string:
int castAscii = (int) UserInput.getText();
DisplayText.setText(UserInput.getText() + " = " + castAscii);
In case UserInput.getText()
returns a string, you can convert it into a character array and then iterate through it to combine the output. 如果
UserInput.getText()
返回一个字符串,则可以将其转换为字符数组,然后对其进行迭代以合并输出。
String userInput = UserInput.getText();
String output = userInput + "=";
for (int i = 0; i < userInput.length(); i++) {
int castAscii = (int) userInput.toCharArray()[i];
output += castAscii;
if (i < userInput.length()) {
output += ",";
}
}
DisplayText.setText(output);
Using a framework like apache commons-lang would make for a more elegant solution, but this will work. 使用诸如apache commons-lang之类的框架将是一个更优雅的解决方案,但这将起作用。
you set the ch='b'.so always you convert the "b" and ignore the input. 设置ch ='b'。因此,总是转换“ b”而忽略输入。
you must set the ch
to what the user entered. 您必须将
ch
设置为用户输入的内容。
as I mentioned in comments,this is an example code to clarify the process. 正如我在评论中提到的那样,这是一个示例代码,用于阐明该过程。
String s = "hello";
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
System.out.println(chars[i]);
int ascii = (int) chars[i];
System.out.println(ascii);
}
you can write scanner.nextline() instead of "hello" next to String s
to get the string from the user. 你可以写旁边字符串scanner.nextline(),而不是“你好”
s
来获取用户的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.