gpt4 book ai didi

java - 如何接收索引并显示其 ASCII 字符?

转载 作者:行者123 更新时间:2023-11-30 04:31:23 27 4
gpt4 key购买 nike

我输入了一个数字 (0-127),并且想要显示具有该索引的 ASCII 字符。到目前为止,我只用我自己的变量实现了这一点。有人可以解释一下如何使用输入来执行此操作吗?

我的代码:

import java.util.Scanner;

public class CharCode {
public static void main (String [] args) {
Scanner input = new Scanner(System.in);
// obtain index
System.out.print("Enter an ASCII code: ");
String entry = input.next();
// How do I get a char with the inputted ASCII index here?

// I can do it with my own variable, but not with input:
int i = 97;
char c = (char) i; // c is now equal to 'a'
System.out.println(c);
}
}

最佳答案

我认为您想输入用户任何 ASCII 值,它将以字符值显示。为此,您需要进行更改,因为您必须对用户输入执行这些操作。

int entry = input.nextInt(); // get the inputted number as integer
// and
char c = (char) entry;

对于您当前的实现

//entry has to be String of numbers otherwise it will throw NumberFormatException.
char c = (char) (Integer.parseInt(entry)); // c will contain 'a'

关于java - 如何接收索引并显示其 ASCII 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14574390/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com