簡體   English   中英

返回帶有int的char的方法

[英]method that returns char with int

有人可以向我解釋此方法嗎,為什么返回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++;
}

為什么這是錯誤的? 任何提示和幫助將不勝感激。

抱歉,這可能有點混亂,請隨時編輯或詢問有關此帖子的任何問題。

Java中的char (和其他原始類型)就像int一樣。

如JLS所說

如果變量的類型為byte,short或char,並且常量表達式的值可表示為變量的類型,則可以使用縮窄的原始轉換。

因此,就像上一個問題的上一個回答一樣 ,您必須強制轉換或更改返回類型,因為:

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

要么

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM