2 回答

TA贡献1841条经验 获得超3个赞
我不确定你的 chopper 类做了什么,但我认为它将输入字符串拆分为空格。如果是这种情况,您可能会在第一个方法 howMany() 中通过调用 chopper.Next() 索引到斩波器的末尾,直到它位于输入的末尾。如果您已经指向斩波器的末端,则在另一个方法中对 chopper.Next() 的下一次调用将为空。
我推荐以下内容:
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;
}

TA贡献1765条经验 获得超5个赞
我假设这是一项学术练习,您必须使用 Scanner 和一种方法解决您的问题。您的代码中的问题是您为每个方法使用/传递相同的扫描仪,但是在方法 howMany (第一次调用)中,代码消耗了您输入的所有标记。由于您无法将扫描仪重新设置为从输入的开头重新开始,因此可以声明三个扫描仪(再次,我假设这是一个学术练习,您必须使用扫描仪解决它)并传递每个扫描仪到你的方法。提示:如果不想使用 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;
}
添加回答
举报