【问题标题】:Character to ASCII字符转 ASCII
【发布时间】:2021-11-11 01:43:05
【问题描述】:
import java.util.Scanner;

public class ASCIIvalue
{
    public static void main(String[] arg)
    {
        Scanner input=new Scanner(System.in);
        char ch;

        int ascii=(int)ch;

        System.out.println("Enter you any character: ");

        ch=input.next().charAt(0);
        System.out.println("The ASCII for this character"+ ch +"is" +ascii);

        System.out.println("");

    }
}

在上面的代码中,我试图从用户那里获取输入(char),然后将其转换为它的 ASCII 值,但我收到错误 Variable character might not have been initialized

【问题讨论】:

  • 请在标签中添加编程语言,本例添加Java

标签: java char ascii


【解决方案1】:

该错误表示您正在尝试访问未初始化的变量。

int ascii = (int) ch;

正如您在此处看到的,您正在尝试访问 ch,但它没有值。

要修复它,请将int ascii = (int) ch; 移动到输入下方。

import java.util.Scanner;

public class ASCIIvalue
{
    public static void main(String[] arg)
    {
        Scanner input=new Scanner(System.in);
        char ch;

        System.out.println("Enter you any character: ");
        ch=input.next().charAt(0);

        int ascii = (int) ch;

        System.out.println("The ASCII for this character " + ch + " is " + ascii);

        System.out.println("");

    }
}

输出

Enter you any character:
a

The ASCII for this character a is 97

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多