我需要从用户那里获取输入。他们可以创建一朵新的花。用户告诉我花的名称(字符串),花的颜色(字符串),花上刺的数量(整数)和花的气味(字符串)。我使用一个名为input的单个扫描仪来获取所有这些信息。但是,它无法正常工作。在获取到刺的数量后,程序会询问用户花的气味,但它不会让我输入答案。然而,我创建了第二个名为input2的扫描仪来获取刺的数量,现在它可以正常工作了。以下是代码:
import java.util.Scanner;
import java.util.ArrayList;
public class AssignmentTwo {
static ArrayList<FlowerClass> flowerPack = new ArrayList<FlowerClass>();
public static void main(String[] args){
Scanner input = new Scanner(System.in);
while(true){
System.out.println("1. Add flower to flowerpack.");
System.out.println("2. Remove flower from the flowerpack.");
System.out.println("3. Search for a flower in the flowerpack.");
System.out.println("4. Display the flowers in the flowerpack.");
int userChoice = input.nextInt();
switch(userChoice){
case 1:
addFlower();
break;
case 2:
//removeFlower();
break;
case 3:
//searchFlower();
break;
case 4:
displayFlowers();
break;
case 5:
System.out.println("Goodbye!");
System.exit(0);
}
}
}
public static void addFlower(){
Scanner input = new Scanner(System.in);
System.out.println("What is the flower's name?");
String desiredName = input.nextLine();
System.out.println("What is the flower's color?");
String desiredColor = input.nextLine();
System.out.println("How many thorns does it have?");
Scanner input2 = new Scanner(System.in);
int desiredThorns = input2.nextInt();
System.out.println("What does it smell like?");
String desiredSmell = input.nextLine();
flowerPack.add(new FlowerClass(desiredName, desiredColor, desiredThorns, desiredSmell));
}
public static void displayFlowers(){
for (FlowerClass flower: flowerPack){
System.out.println(flower.getName());
}
System.out.println("Number of flowers in pack: " + FlowerClass.numberFlowers());
}
}
如果你查看我的addFlower()函数,你会看到我创建一个Scanner input2,并使用它来获取新花的刺数量的int值。之前,我使用函数中的第一个Scanner实例来获取刺的输入,但是这样无法正常工作。旧函数如下:
public static void addFlower(){
Scanner input = new Scanner(System.in);
System.out.println("What is the flower's name?");
String desiredName = input.nextLine();
System.out.println("What is the flower's color?");
String desiredColor = input.nextLine();
System.out.println("How many thorns does it have?");
int desiredThorns = input.nextInt();
System.out.println("What does it smell like?");
String desiredSmell = input.nextLine();
flowerPack.add(new FlowerClass(desiredName, desiredColor, desiredThorns, desiredSmell));
}
第一个版本的函数为什么不能工作?我通过使用新的Scanner修复了它,但是我不明白为什么第一个版本不能工作。当您尝试为不同种类的输入使用单个扫描器时,扫描器是否会混淆?我正在查看Java教程文档中的扫描教程,但没有找到答案。感谢您的时间!