有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

返回带有int的char的java方法

有人能给我解释一下这个方法吗?为什么返回的是char而不是int

public static int fgetc(InputStream stream)
{
    char ToRet = '\0';
    if (InStream.isEmpty())
    {
         try
         {
              ToRet = (char) stream.read();
              if (ToRet == CR)
                    Toret = (char) stream.read();
              if ((int) ToRet == 0xFFFF)
                    return EOF;
         }
         catch (EOFException eof)
         {
               return EOF;
         }
         catch (IOException ioe)
         {
                writeline ("Unexpected IO Exception caught!\n", System.out);
                writeline (ioe.toString(),System.out);
         }
     }
     else
           ToRet = ((MYLibCharacter) Instream.pop ()).charValue();
return ToRet;
}

假设您希望将用户输入的值存储为字符,直到检测到换行符

int index = 0;
while (message[index] != '\n\)
{
    message[index] = fgetc(System.in);
    index++;
}

为什么这是错误的?? 任何提示和帮助都将不胜感激

抱歉,这可能有点混乱,请随意编辑或问我任何关于这篇文章的问题


共 (1) 个答案

  1. # 1 楼答案

    Java中的char(和其他基本类型)与int类似

    As in JLS says

    A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

    因此,在my previous answeryour previous question中,必须强制转换它或更改返回类型,因为:

    char c = 'A' + 1;
    char c = 45;
    

    或者

    char c = 'A';
    c = c++;