用户在Java中的基本阅读输入 [英] basic reading input from user in java

查看:152
本文介绍了用户在Java中的基本阅读输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取一个字符并将其存储到char[]数组中,这是我的方法,称为getaline

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++;
}

和我的fgetc方法:

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

我应该在fgetc里面放些什么,以便我可以从用户那里收集输入信息?

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

推荐答案

您的代码期望使用char,但是您在此处返回int:

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

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

您可以

  • 更改方法签名以返回char.

public static char fgetc(InputStream stream)
//            ↑ tells method will return a char

  • 将值返回到char

    投射转换(§5.5)将表达式的类型转换为由强制转换运算符(

    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
    

  • 这篇关于用户在Java中的基本阅读输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆