将用户输入读取为String并将其与任何ArrayList进行比较以进行验证

时间:2016-02-04 18:19:37

标签: java

我正在为一个有两个班级的植物苗圃开展一个项目; PlantNursery和Plant。用户被提升了4个问题。 1)添加植物,2)列出所有植物,3)编辑植物,4)退出。我得到1分,2分和4分正常工作。我的问题在于选项3.我在数组中显示当前植物列表,并要求用户通过它的常用名称选择一个。然后我存储String并将其与if语句进行比较。 if语句未按预期工作。我收到错误消息:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
    at java.util.ArrayList.rangeCheck(ArrayList.java:653)
    at java.util.ArrayList.get(ArrayList.java:429)
    at plantnursery.PlantNursery.main(PlantNursery.java:92)
C:\Users\diggz\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 52 seconds)

植物类:

package plantnursery;

public class Plant 
{
    //Variables
    private String commonName, scientificName;
    private double maxHeight, price;
    private boolean fragile;

    //Constructor
    public Plant(String commonName, String scientificName, double maxHeight, 
            double price, boolean fragile)
    {
        this.maxHeight = maxHeight;
        this.price = price;
        this.commonName = commonName;
        this.scientificName = scientificName;
        this.fragile = fragile;
    }

    public double getMaxHeight()
    {
        return maxHeight;
    }

    public void setMaxHeight(double maxHeight)
    {
        this.maxHeight = maxHeight;
    }

    public double getPrice()
    {
        return price;
    }

    public void setPrice(double price)
    {
        this.price = price;
    }

    public String getCommonName()
    {
        return commonName;
    }

    public void setCommonName(String commonName)
    {
        this.commonName = commonName;
    }

    public String getScientificName()
    {
        return scientificName;
    }

    public void setScientificName(String scientificName)
    {
        this.scientificName = scientificName;
    }

    public boolean isFragile()
    {
        return fragile;
    }

    public void setFragile(boolean fragile)
    {
        this.fragile = fragile;
    }

    @Override
    public String toString() {
        return "Plant{" + "commonName= " + commonName + ", scientificName= " 
                + scientificName + ", maxHeight= " + maxHeight + ", price= " 
                + price + ", fragile= " + fragile + '}';
    } 
}

PlantNursery类:

package plantnursery;

import java.util.ArrayList;
import java.util.Scanner;


public class PlantNursery
{

    public static void main(String[] args)
    {
        //Variables to hold user input.
        double userHeight, userPrice;
        String userComName, userSciName, blankLine;
        boolean userFragile;
        int ans, choice;
        //Reference variable to an object.
        Plant p;
        //Scanner for user input.
        Scanner scan = new Scanner(System.in);
        //ArrayList to store all the plants in.
        ArrayList<Plant> plantList = new ArrayList<>();

        //While loop asking the user to create new plants and store them
        //in the the ArrayList. Edit any of the plants already in the ArrayList
        //or quit the program.
        while(true)
        {
            //Ask the user what they want to do.
            System.out.println("What do you want to do?\n1. Add a plant. "
                    + "\n2. List all plants.\n3. Edit a plant. \n4. Quit.");
            //Store answer
            ans = scan.nextInt();

            //Choice 1. Add a new plant into the ArrayList.
            if(ans == 1)
            {
                //Get rid of buffer overflow from int ans.
                blankLine = scan.nextLine();

                //Ask the user for input for a new plant object.
                System.out.println("Please enter the common name of the plant:");
                userComName = scan.nextLine();
                System.out.println("Please enter the scienitific name of the plant: ");
                userSciName = scan.nextLine();
                System.out.println("Please enter the maximum height (in feet) of the plant: ");
                userHeight = scan.nextDouble();
                System.out.println("Please enter the price of the plant: ");
                userPrice = scan.nextDouble();
                System.out.println("Please enter if the plant is fragile (true or false): ");
                userFragile = scan.nextBoolean();

                //Create the new plant object.
                p = new Plant(userComName, userSciName, userHeight, userPrice, 
                        userFragile);

                //Add the plant object to the ArrayList.
                plantList.add(p);
            }

            //Choice 2. Display all plant(s) in the ArrayList.
            if(ans == 2)
            {
                //List all the current plants in the ArrayList.
                for(Plant curList : plantList)
                {
                    System.out.println(curList);
                }
            }

            //Choice 3. Edit information on plant(s) in ArrayList.
            if(ans == 3)
            {
                //Allows the user to edit until they wish to quit.
                while(true)
                {
                    //Counter for ArrayList
                    int i;
                    //String to hold which plant the user wishes to edit.
                    String userAns;
                    //Ask the user which plant they wish to edit.
                    System.out.println("Which plant to wish to edit (choose the common name)?");
                    //Display the plant(s).
                    for(i = 0; i < plantList.size(); i++)
                    {
                        System.out.println(plantList.get(i));
                    }   
                    //Get the user input and compare it to the Common Name
                    blankLine = scan.nextLine();
                    userAns = scan.nextLine();

                 if(userAns.equalsIgnoreCase(plantList.get(i).getCommonName())) //PROBLEM CODE
                    {
                        //Ask what the user wishes to edit.
                        System.out.println("What do you wish to edit?\n1. Common Name."
                                + "\n2. Scientific Name.\n3. Maximum Height.\n4. Price"
                                + "\n5. Is it fragile (true or false)?\n6. Quit.");
                        //Get user choice.
                        choice = scan.nextInt();
                        //Choice 1
                        if(choice == 1)
                        {
                            System.out.println("What is the new Common Name? ");
                            String newComName = scan.nextLine();
                            plantList.get(i).setCommonName(newComName);
                        }
                        //Choice 2
                        if(choice == 2)
                        {
                            System.out.println("What is the new Scientific Name? ");
                            String newSciName = scan.nextLine();
                            plantList.get(i).setScientificName(newSciName);
                        }
                        //Choice 3
                        if(choice == 3)
                        {
                            System.out.println("What is the new Maximum Height? ");
                            double newHeight = scan.nextDouble();
                            plantList.get(i).setMaxHeight(newHeight);
                        }
                        //Choice 4
                        if(choice == 4)
                        {
                            System.out.println("What is the new Price?");
                            double newPrice = scan.nextDouble();
                            plantList.get(i).setPrice(newPrice);
                        }
                        //Choice 5
                        if(choice == 5)
                        {
                            System.out.println("Is the plant Fragile (true or false)? ");
                            boolean newFragile = scan.nextBoolean();
                            plantList.get(i).setFragile(newFragile);
                        }
                        //Choice 6
                        if(choice == 6)
                        {
                            break;
                        }
                    }
                }  
            }
            //Choice 4. End program.
            if(ans == 4)
            {
                break;
            }
        }
    } 
}

好的,所以我将第三个选项更改为switch语句。现在我遇到的问题是我只能进行一次编辑。在第一次编辑之后,当我尝试选择另一个工厂或同一个工厂进行编辑时,它没有阅读它,并一直问我同样的问题。

代码:

//Choice 3. Edit information on plant(s) in ArrayList.
            if(ans == 3)
            {
                OUTER:
                while (true) {
                    int i;
                    String userAns;
                    System.out.println("Which plant to wish to edit (choose the common name)?");
                    for(i = 0; i < plantList.size(); i++)
                    {
                        System.out.println(plantList.get(i));
                    }
                    blankLine = scan.nextLine();
                    userAns = scan.nextLine();
                    if (userAns.equalsIgnoreCase(plantList.get(i-1).getCommonName())) {
                        System.out.println("What do you wish to edit?\n1. Common Name."
                                + "\n2. Scientific Name.\n3. Maximum Height.\n4. Price"
                                + "\n5. Is it fragile (true or false)?\n6. Quit.");
                        choice = scan.nextInt();
                        //Choices
                        switch (choice) 
                        {
                            //Choice 1
                            case 1:
                                System.out.println("What is the new Common Name? ");
                                blankLine = scan.nextLine();
                                String newComName = scan.nextLine();
                                plantList.get(i-1).setCommonName(newComName);
                                break;
                            //Choice 2
                            case 2:
                                System.out.println("What is the new Scientific Name? ");
                                blankLine = scan.nextLine();
                                String newSciName = scan.nextLine();
                                plantList.get(i-1).setScientificName(newSciName);
                                break;
                            //Choice 3
                            case 3:
                                System.out.println("What is the new Maximum Height? ");
                                double newHeight = scan.nextDouble();
                                plantList.get(i-1).setMaxHeight(newHeight);
                                break;
                            //Choice 4
                            case 4:
                                System.out.println("What is the new Price?");
                                double newPrice = scan.nextDouble();
                                plantList.get(i-1).setPrice(newPrice);
                                break;
                            //Choice 5
                            case 5:
                                System.out.println("Is the plant Fragile (true or false)? ");
                                boolean newFragile = scan.nextBoolean();
                                plantList.get(i-1).setFragile(newFragile);
                                break;
                            //Choice 6
                            case 6:
                                break OUTER;
                            default:
                                break;
                        }
                    }
                }  
            }

3 个答案:

答案 0 :(得分:1)

ArrayList索引从0开始,因此您必须执行plantList.get(i-1).setPrice(newPrice);

答案 1 :(得分:1)

您正在开始索引0.因此,如果您键入2,则表示您尝试访问3个值 array[0], array[1], array[2]

更改for(i = 0; i < plantList.size(); i++)for(i = 1; i < plantList.size(); i++)

如果您不想更改for循环,则需要将plantList.get(i)更改为plantList.get(i-1)以确保其在范围内

答案 2 :(得分:1)

i

您已将plantList.size()增加到plantList.get(i).getCommonName()。当您使用i访问列表时,Map已经大于最大索引。

您可能不应该将循环外定义的变量用作循环中的计数器。

您是否考虑过.csproject而不是通过列表进行搜索?