我正在学习Java,并且正在制作一个库。我想在同一扫描仪上使用三种方法,但扫描仪每次都会被清除。
我们在课堂上使用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
我知道它会在第一个方法运行后清除扫描器,不管它的顺序是什么。即使我在方法的第一行中将Scanner转换为另一种数据类型,它仍然会清除原始数据类型。谢谢!
发布于 2019-02-11 23:55:44
我不确定您的chopper类是做什么的,但我假设它将输入字符串拆分为空格。如果是这样的话,您可以通过调用chopper.Next()来索引到第一个方法howMany()中的斩波器的末尾,直到它到达输入的末尾。如果您已经指向了斩波器的末尾,则另一个方法中对chopper.Next()的下一次调用将为null。
我会推荐以下几点:
public static String howMany(Scanner chopper){
String x = "";
int y = 0;
int doubleCount=0;
int intCount =0;
while(chopper.hasNext()){
y++;
if (chopper.hasNextDouble()){
doubleCount++;
}
if(chopper.hasNextInt()){
intCount++;
}
x = chopper.next();
}
return x+y+" "+ intCount + " " + doubleCount;
}发布于 2019-02-12 00:26:47
我会假设这是一个学术练习,你必须解决你的问题与扫描仪和一个方法的计数。代码中的问题是,您为每个方法使用/传递相同的扫描器,但是在方法howMany (是第一个调用的方法)中,代码使用输入的所有标记。由于您不能将Scanner重新设置为从输入的开头重新开始,因此一个解决方案可以是声明三个Scanner(同样,我假设这是一个学术练习,您必须使用Scanner解决它),并将每个Scanner传递给您的方法。提示:如果不想使用变量x,则不需要将chopper.next()的结果赋给变量x,只需调用chopper.next()即可。
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
String typedStuff = kb.nextLine();
Scanner chopperHowMany = new Scanner(typedStuff);
Scanner chopperHowManyInts = new Scanner(typedStuff);
Scanner chopperHowManyDoubles = new Scanner(typedStuff);
System.out.println(howMany(chopperHowMany));
System.out.println(howManyInts(chopperHowManyInts));
System.out.println(howManyIntsAndDoubles(chopperHowManyDoubles.reset()));
}
public static int howMany(Scanner chopper) //
{
int y = 0;
while (chopper.hasNext()) {
y++;
chopper.next();
}
return y;
}
public static int howManyInts(Scanner chopper) {
int y = 0;
while (chopper.hasNext()) {
if (chopper.hasNextInt()) {
y++;
}
chopper.next();
}
return y;
}
public static int howManyIntsAndDoubles(Scanner chopper) {
int y = 0;
while (chopper.hasNext()) {
if (chopper.hasNextDouble()) {
y++;
}
chopper.next();
}
return y;
}https://stackoverflow.com/questions/54634059
复制相似问题