【发布时间】:2019-02-11 15:38:47
【问题描述】:
我正在学习 Java,并且正在制作一个库。我想在同一个Scanner上使用三种方法,但是每次都会清空scanner。
我们在课堂上使用 Jcreator,但我的老师也无法弄清楚发生了什么。唯一有效的是
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
String typedStuff = kb.nextLine();
Scanner chopper = new Scanner(typedStuff);
System.out.println(howMany(chopper));
System.out.println(howManyInts(chopper));
System.out.println(howManyIntsAndDoubles(chopper));
}
public static int howMany(Scanner chopper) //
{
String x = "";
int y = 0;
while(chopper.hasNext())
{
y++;
x = chopper.next();
}
return y;
}
public static int howManyInts(Scanner chopper)
{
String x = "";
int y = 0;
while(chopper.hasNext())
{
if (chopper.hasNextInt())
{
y++;
}
x = chopper.next();
}
return y;
}
public static int howManyIntsAndDoubles(Scanner chopper)
{
String x = "";
int y = 0;
while(chopper.hasNext())
{
if (chopper.hasNextDouble())
{
y++;
}
x = chopper.next();
}
return y;
}
如果我输入“yes 5.2 2 5.7 6 no”,那么我的输出是: 6 0 0
但它应该是: 6 2 4
我知道它会在第一个方法运行后清除扫描仪,无论它的顺序如何。即使我在方法的第一行将扫描仪转换为另一种数据类型,它仍然会清除原始数据类型。谢谢!
【问题讨论】:
-
这是因为您正在迭代第一个方法中的所有输入,所以当涉及到第二个函数时,扫描仪没有什么可以扫描的了。
-
用扫描仪来做这件事很奇怪。使用字符串会更容易。并使用 stringobject.split(" ") 方法(它将您的输入字符串拆分为一个数组。每个数组条目都包含在“空格符号”的拆分部分。然后您可以轻松地使用数组和 for 或while 循环。
-
如果你不明白,我可以发布正确的答案。嗯
标签: java methods java.util.scanner