Search code examples
javainputuser-inputfgetc

method that returns char with int


Can someone explain this method to me and why is this returning char instead of 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;
}

and lets say you want to store the value that the user input as a character until the newline is detected,

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

why is this wrong?? Any tips and help would be much appreciated.

sorry this might be a little messy, feel free to edit or ask me any questions regarding this post.


Solution

  • char (and other primitive types) in Java are like int's.

    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.

    So as in my previous answer to your previous question, you must cast it or change return type, because:

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

    or

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