我正在学习 Java,我正在制作一个库。我想在同一个 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
我知道它在第一种方法运行后清除扫描仪,无论它的顺序是什么。即使我在方法的第一行将扫描仪转换为另一种数据类型,它仍然会清除原始数据类型。谢谢!
偶然的你
POPMUISE
相关分类