我如何更改此方法以获取字符串而不是整数
这是原始代码:
public static int getInt ()
{
Scanner in = new Scanner (System.in) ;
if (in.hasNextInt())
{
int a = in.nextInt() ;
return a ;
}
else
{
System.out.println ("try again:") ;
return getInt () ;
}
}
它检查并查看它接收到的输入是否是 int。如果是,则返回 int,如果不是,则告诉您重试并重新运行。
这就是我试图改变它的方法:
public static String getIns ()
{
Scanner in = new Scanner (System.in) ;
if (in.hasNextString())
{
String a = in.nextString() ;
return a ;
}
else
{
System.out.println ("try again:") ;
return getIns () ;
}
}
但这不起作用。我查看了扫描仪类的文档,我认为问题是没有诸如 in.hasNextString
或 in.nextString
这样的方法 扫描仪类中的哪些方法可以我用来做我想做的事?
here is the original code:
public static int getInt ()
{
Scanner in = new Scanner (System.in) ;
if (in.hasNextInt())
{
int a = in.nextInt() ;
return a ;
}
else
{
System.out.println ("try again:") ;
return getInt () ;
}
}
This checks and sees if the input it receives is an int. If it is then it returns the int, if not it tells you to try again and re-runs.
This is what i tried to do to change it:
public static String getIns ()
{
Scanner in = new Scanner (System.in) ;
if (in.hasNextString())
{
String a = in.nextString() ;
return a ;
}
else
{
System.out.println ("try again:") ;
return getIns () ;
}
}
This doesn't work though. I looked through the documentation for the scanner class and i think the problem is that there is no such method as in.hasNextString
or in.nextString
What methods from the scanner class can i use to do what i intend these to do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该阅读文档< /a>.
您正在寻找
next
和hasNext
。You should read the documentation.
You're looking for
next
andhasNext
.使用
Scanner.hasNext( )
:Use
Scanner.hasNext()
: