basic reading input from user in java

南笙酒味 提交于 2019-12-08 15:13:52

问题


I want to read a character and store it into the char[] array and here is my method called getaline

public static int getaline(char message[], int maxlength)
{
     int index = 0;
     while (message[index] != '\n')
     {
         message[index] = fgetc(System.out);
         index++;
     }
     index++;
}

and my fgetc method:

public static int fgetc(InputStream stream)

and this method should returns a character from the input stream.

But i keep getting an error message when i compile:

error: possible loss of precision

message[index] = fgetc(System.in);
                       ^
required: char

found:    int

what should i put inside fgetc so that i can collect input from the user??


回答1:


Your code is expecting a char, but you return an int here:

public static int fgetc(InputStream stream)
//            ↑ tells method will return an int

You can

  • Change method signature to return a char.

    public static char fgetc(InputStream stream)
    //            ↑ tells method will return a char
    
  • Cast returned value to char

    Casting conversion (§5.5) converts the type of an expression to a type explicitly specified by a cast operator (§15.16).

    message[index] = (char) fgetc(System.in);
    //               ↑ cast returning value to a char
    


来源:https://stackoverflow.com/questions/32861671/basic-reading-input-from-user-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!