问题
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