java编程:如何从控制台获取字符型数据? 如下图,该如何修改?谢谢!

如题所述

in.next();从控制台输入的是字符型的,sex是char类型,类型不匹配追问

char不就是字符型的吗?

追答

打错了,是字符串,String类型

追问

我定义的sex就是字符型的呀,有什么问题呢?

追答

你定义的sex是char类型,不是String类型,

这是javaapi文档中对next()方法的解释,返回的是一个String类型
public String next(String pattern)

Returns the next token if it matches the pattern constructed from the specified string. If the match is successful, the scanner advances past the input that matched the pattern.
An invocation of this method of the form next(pattern) behaves in exactly the same way as the invocation next(Pattern.compile(pattern)).
Parameters:
pattern - a string specifying the pattern to scan
Returns:
the next token
Throws:
NoSuchElementException - if no such tokens are available
IllegalStateException - if this scanner is closed

追问

那可不可以用字符型的呢?一定要用字符串?因为我只需要输入一个字(男或女)就可以了。

追答

你用这个吧,
Scanner里面没有返回char的方法,只能转换一下,其实还比较麻烦。
String s=input.next();
char sex=s.charAt(0);

追问

貌似也不行,还是用String好了。Anyway,thank you very much for wasting your so much time!

温馨提示:答案为网友推荐,仅供参考
相似回答