简体   繁体   English

我应该如何使用用户输入从多维数组存储数组

[英]How i should store array from a multidimensional array with user input

yes, this is my homework. 是的,这是我的作业。 But i am stuck and have been for days. 但是我被困住了好几天了。 (horrible teacher, horrible lessons. this teacher will never respond to me or anyone about anything) (可怕的老师,可怕的教训。这位老师永远不会回应我或任何人的任何事情)

I have seen something like this on here before but never seen or understood their answers. 我以前在这里看到过类似的内容,但从未看过或理解过他们的答案。

In this program, the user inputs a state, then it outputs the states bird and its flower. 在此程序中,用户输入一个状态,然后输出状态鸟及其花。 after the user types none, it should give them a summery of everything they typed in a row. 在用户不输入任何内容后,它应该使他们对自己连续输入的所有内容有所了解。 State, Bird, Flower. 状态,鸟,花。 I have not a clue how to do this... You do not have to tell me how, that is fine. 我不知道如何执行此操作...您不必告诉我如何,这很好。 but could you please guide me, in a non vague way haha. 但是你能不能用模糊的方式指导我哈哈。

import java.util.Scanner;

public class TheStatesTester {
public static void main(String[] args) {

    String theState [][] =  {
            {"Alabama", "Northern Flicker","Camelia"},
            {"Alaska", "Willow PTarmigan","ForgetMeNot"},
            {"Arizona", "Cactus Wren","Saguaro Cactus Blossom"},
            {"Arkansas", "Mockingbird","Apple Blossom"},
            {"California", "California Quail","California Blossom"},
            {"Colorado", "Lark Bunting","Rocking Mountain Columbine"},
            {"Connecticut", "American Robin","Mountain Laurel"},
            {"Delaware", "Blue Hen Chicken","Peach Blossom"},
            {"Flordia", "Mockingbird","Orange Blossom"},
            {"Georgia", "Brown Thrasher","Cherokee Rose"},
            {"Hawaii", "Nene","Hibiscus"},
            {"Idaho", "Peregrine Falcon","Mock Orange"},
            {"Illinois", " Northern Cardinal","Purple Violet"},
            {"Indiana", "Northern Cardinal","Peony"},
            {"Iowa", "Eastern Goldrinch","Wild Prairie Rose"},
            {"Kansas", "Western Meadowlark","Sunflower"},
            {"Kentucky", "Northen Cardinal","Golden Rod"},
            {"Louisiana", "Brown Pelican","Magnolia"},
            {"Maine", "Black-capped Chickadee","White Pine Tassel and Cone"},
            {"Maryland", "Baltimore Oriole","Black-Eyes Susan"},
            {"Massachusetts", "Black-Capped Chickadee","Mayflower"},
            {"Michigan", "Robin Redbreast","Apple Blossom"},
            {"Minnesota", "Common Loon","Pink and White ladyslipper"},
            {"Mississippi", "Wood Duck","Magnolia"},
            {"Missouri", "Eastern Bluebird","Hawthorn"},
            {"Montana", "Western Meadowlark","Bitterroot"},
            {"Nebraska", "Western Medowlark","Goldenrod"},
            {"Nevada", "Mountain Bluebird","Sagebush"},
            {"New Hampshire", "Purple Finch","Purple Lilac"},
            {"New Jersey", "Eastern Goldfinch","Violet"},
            {"New Mexico", "Roadrunner","Yucca"},
            {"New York", "Bluebird","Rose"},
            {"North Carolina", "Cardinal","Flowering Dogwood"},
            {"North Dakota", "Western Meadowlark","Wild Prairie Rose"},
            {"Ohio", "Cardinal","Scarlet Carnation"},
            {"Oklahoma", "Scissor-tailed Flycatcher","Mistletoe"},
            {"Oregon", "Western Medowlark","Orange Grape"},
            {"Pennsylvania", "Ruffed Grouse","Mountain Laurel"},
            {"Rhode Island", "Rhode Island Red","Violet"},
            {"South Carolina", "Great Carolina Wren","Yellow Jessamine"},
            {"South Dakota", "Ring-necked Pheasant","Pasque Flower"},
            {"Tennessee", "Mocking Bird","Iris"},
            {"Texas", "Mocking Bird","Texas Bluebonnet"},
            {"Utah", "Common American Gull","Sego Lily"},
            {"Vermont", "Hermit Thrush","Red Clover"},
            {"Virginia", "Cardinal","Flowering Dogwood"},
            {"Washington", "Willow Goldfinch","Coast Rhodoendron"},
            {"West Virginia", "Cardinal","Rhododendron"},
            {"Wisconsin", "Robin","Violet"},
            {"Wyoming", "Western Medowlark","Indian Paintbrush"},

        };




    Scanner input1 = new Scanner(System.in);

    while (true) {
    System.out.println("Enter a State or None to exit: ");
    String states = input1.nextLine();

    int position=getBirdFlower(theState, states);
    if (states.trim().equalsIgnoreCase("None")){
            System.out.println("**** Thank you *****\r\n" + 
                    "A summary report for each State, Bird, and Flower is: " );
            break;
        }
    else {

        if(position!=-1)
        {
            System.out.println("Bird: "+theState[position][1]);
            System.out.println("Flower: "+theState[position][2]);              
        }
        else
            System.out.println("Invalid state entered");

    //  for (int i=0; i<state.length;i)
        //  for (int j=0;j<state[i].length;j)
            //  System.out.println(state[i][j]);

        }

    }



            }
public static int getBirdFlower(String theState[][], String state)
{
    int position = -1;
    boolean found=false;
    for (int index = 0; index < theState.length && !found; index++)
    {
        if(theState[index][0].equalsIgnoreCase(state))
        position = index;
    }
    return position;
}

        }

I added some comment to your code for understand clearly. 我在您的代码中添加了一些注释,以使您清楚理解。 Please read carefully. 请仔细阅读。

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

public class TheStatesTester {
    public static void main(String[] args) {

        String theState[][] = {
                {"Alabama", "Northern Flicker", "Camelia"},
                {"Alaska", "Willow PTarmigan", "ForgetMeNot"},
                {"Arizona", "Cactus Wren", "Saguaro Cactus Blossom"},
                {"Arkansas", "Mockingbird", "Apple Blossom"},
                {"California", "California Quail", "California Blossom"},
                {"Colorado", "Lark Bunting", "Rocking Mountain Columbine"},
                {"Connecticut", "American Robin", "Mountain Laurel"},
                {"Delaware", "Blue Hen Chicken", "Peach Blossom"},
                {"Flordia", "Mockingbird", "Orange Blossom"},
                {"Georgia", "Brown Thrasher", "Cherokee Rose"},
                {"Hawaii", "Nene", "Hibiscus"},
                {"Idaho", "Peregrine Falcon", "Mock Orange"},
                {"Illinois", " Northern Cardinal", "Purple Violet"},
                {"Indiana", "Northern Cardinal", "Peony"},
                {"Iowa", "Eastern Goldrinch", "Wild Prairie Rose"},
                {"Kansas", "Western Meadowlark", "Sunflower"},
                {"Kentucky", "Northen Cardinal", "Golden Rod"},
                {"Louisiana", "Brown Pelican", "Magnolia"},
                {"Maine", "Black-capped Chickadee", "White Pine Tassel and Cone"},
                {"Maryland", "Baltimore Oriole", "Black-Eyes Susan"},
                {"Massachusetts", "Black-Capped Chickadee", "Mayflower"},
                {"Michigan", "Robin Redbreast", "Apple Blossom"},
                {"Minnesota", "Common Loon", "Pink and White ladyslipper"},
                {"Mississippi", "Wood Duck", "Magnolia"},
                {"Missouri", "Eastern Bluebird", "Hawthorn"},
                {"Montana", "Western Meadowlark", "Bitterroot"},
                {"Nebraska", "Western Medowlark", "Goldenrod"},
                {"Nevada", "Mountain Bluebird", "Sagebush"},
                {"New Hampshire", "Purple Finch", "Purple Lilac"},
                {"New Jersey", "Eastern Goldfinch", "Violet"},
                {"New Mexico", "Roadrunner", "Yucca"},
                {"New York", "Bluebird", "Rose"},
                {"North Carolina", "Cardinal", "Flowering Dogwood"},
                {"North Dakota", "Western Meadowlark", "Wild Prairie Rose"},
                {"Ohio", "Cardinal", "Scarlet Carnation"},
                {"Oklahoma", "Scissor-tailed Flycatcher", "Mistletoe"},
                {"Oregon", "Western Medowlark", "Orange Grape"},
                {"Pennsylvania", "Ruffed Grouse", "Mountain Laurel"},
                {"Rhode Island", "Rhode Island Red", "Violet"},
                {"South Carolina", "Great Carolina Wren", "Yellow Jessamine"},
                {"South Dakota", "Ring-necked Pheasant", "Pasque Flower"},
                {"Tennessee", "Mocking Bird", "Iris"},
                {"Texas", "Mocking Bird", "Texas Bluebonnet"},
                {"Utah", "Common American Gull", "Sego Lily"},
                {"Vermont", "Hermit Thrush", "Red Clover"},
                {"Virginia", "Cardinal", "Flowering Dogwood"},
                {"Washington", "Willow Goldfinch", "Coast Rhodoendron"},
                {"West Virginia", "Cardinal", "Rhododendron"},
                {"Wisconsin", "Robin", "Violet"},
                {"Wyoming", "Western Medowlark", "Indian Paintbrush"},

        };


        Scanner input1 = new Scanner(System.in);
        ArrayList<String> userInputStates = new ArrayList<>();

        while (true) {
            System.out.println("Enter a State or None to exit: ");
            String states = input1.nextLine();

            if (states.trim().equalsIgnoreCase("None")) {
                System.out.println("**** Thank you *****\r\n" +
                        "A summary report for each State, Bird, and Flower is: ");
                //printing the userList
                printUserList(userInputStates);
                break;
            } else {

                //I moved this getBirdFlower method call to heere, because if not none , call from here
                int position = getBirdFlower(theState, states);
                if (position != -1) {
                    System.out.println("Bird: " + theState[position][1]);
                    System.out.println("Flower: " + theState[position][2]);
                    //Add user's found properties to arrayList.
                    userInputStates.add("- State: " + theState[position][0] + " Bird: " + theState[position][1] + " Flower: " + theState[position][2]);
                } else
                    System.out.println("Invalid state entered");
            }

        }


    }

    private static void printUserList(ArrayList<String> userInputStates) {
        //print userInputStates.
        for (String userState : userInputStates) {
            System.out.println(userState);
        }
    }

    public static int getBirdFlower(String theState[][], String state) {
        //you dont need to keep boolean , if found -> return current index
        for (int index = 0; index < theState.length; index++) {
            if (theState[index][0].equalsIgnoreCase(state))
                return index;
        }
        //if not found, return -1
        return -1;
    }

}

Sample output from code ; 代码的样本输出;

 Enter a State or None to exit: Wyoming Bird: Western Medowlark Flower: Indian Paintbrush Enter a State or None to exit: Utah Bird: Common American Gull Flower: Sego Lily Enter a State or None to exit: InvalidState Invalid state entered Enter a State or None to exit: none **** Thank you ***** A summary report for each State, Bird, and Flower is: - State: Wyoming Bird: Western Medowlark Flower: Indian Paintbrush - State: Utah Bird: Common American Gull Flower: Sego Lily 

The trick is to store the user input as he types it. 诀窍是在用户输入内容时将其存储。 In this case I made my life easier by using an ArrayList but this can be done with normal arrays as well but there is more work managing the array. 在这种情况下,通过使用ArrayList可以使我的生活更轻松,但是普通数组也可以做到这一点,但是管理数组还有更多工作要做。 I also added some comment explaining each step. 我还添加了一些注释来解释每个步骤。

public class TheStatesTester {
    public static void main(String[] args) {

        String theStates[][] = { { "Alabama", "Northern Flicker", "Camelia" },
                { "Alaska", "Willow PTarmigan", "ForgetMeNot" }, { "Arizona", "Cactus Wren", "Saguaro Cactus Blossom" },
                { "Arkansas", "Mockingbird", "Apple Blossom" },
                { "California", "California Quail", "California Blossom" },
                { "Colorado", "Lark Bunting", "Rocking Mountain Columbine" },
                { "Connecticut", "American Robin", "Mountain Laurel" },
                { "Delaware", "Blue Hen Chicken", "Peach Blossom" }, { "Flordia", "Mockingbird", "Orange Blossom" },
                { "Georgia", "Brown Thrasher", "Cherokee Rose" }, { "Hawaii", "Nene", "Hibiscus" },
                { "Idaho", "Peregrine Falcon", "Mock Orange" }, { "Illinois", " Northern Cardinal", "Purple Violet" },
                { "Indiana", "Northern Cardinal", "Peony" }, { "Iowa", "Eastern Goldrinch", "Wild Prairie Rose" },
                { "Kansas", "Western Meadowlark", "Sunflower" }, { "Kentucky", "Northen Cardinal", "Golden Rod" },
                { "Louisiana", "Brown Pelican", "Magnolia" },
                { "Maine", "Black-capped Chickadee", "White Pine Tassel and Cone" },
                { "Maryland", "Baltimore Oriole", "Black-Eyes Susan" },
                { "Massachusetts", "Black-Capped Chickadee", "Mayflower" },
                { "Michigan", "Robin Redbreast", "Apple Blossom" },
                { "Minnesota", "Common Loon", "Pink and White ladyslipper" },
                { "Mississippi", "Wood Duck", "Magnolia" }, { "Missouri", "Eastern Bluebird", "Hawthorn" },
                { "Montana", "Western Meadowlark", "Bitterroot" }, { "Nebraska", "Western Medowlark", "Goldenrod" },
                { "Nevada", "Mountain Bluebird", "Sagebush" }, { "New Hampshire", "Purple Finch", "Purple Lilac" },
                { "New Jersey", "Eastern Goldfinch", "Violet" }, { "New Mexico", "Roadrunner", "Yucca" },
                { "New York", "Bluebird", "Rose" }, { "North Carolina", "Cardinal", "Flowering Dogwood" },
                { "North Dakota", "Western Meadowlark", "Wild Prairie Rose" },
                { "Ohio", "Cardinal", "Scarlet Carnation" }, { "Oklahoma", "Scissor-tailed Flycatcher", "Mistletoe" },
                { "Oregon", "Western Medowlark", "Orange Grape" },
                { "Pennsylvania", "Ruffed Grouse", "Mountain Laurel" },
                { "Rhode Island", "Rhode Island Red", "Violet" },
                { "South Carolina", "Great Carolina Wren", "Yellow Jessamine" },
                { "South Dakota", "Ring-necked Pheasant", "Pasque Flower" }, { "Tennessee", "Mocking Bird", "Iris" },
                { "Texas", "Mocking Bird", "Texas Bluebonnet" }, { "Utah", "Common American Gull", "Sego Lily" },
                { "Vermont", "Hermit Thrush", "Red Clover" }, { "Virginia", "Cardinal", "Flowering Dogwood" },
                { "Washington", "Willow Goldfinch", "Coast Rhodoendron" },
                { "West Virginia", "Cardinal", "Rhododendron" }, { "Wisconsin", "Robin", "Violet" },
                { "Wyoming", "Western Medowlark", "Indian Paintbrush" },

        };

        Scanner scanner = new Scanner(System.in);
        ArrayList<String> visitedStates = new ArrayList<>();//using this to store the states already asked.

        while (true) {//loop forever... i'm not a fan of this
            System.out.println("Enter a State or None to exit: ");
            String state = scanner.nextLine().trim();//remove extra spaces and set the state

            if ("None".equalsIgnoreCase(state)) {//check if user is done
                System.out
                        .println("**** Thank you *****\r\n" + "A summary report for each State, Bird, and Flower is: ");
                for(String vistedState : visitedStates) {//loop though all the visited states
                    int stateIndex = getStateIndex(theStates, vistedState);//find the index of the visited states
                    System.out.println(Arrays.toString(theStates[stateIndex]));//print out the info for the state
                }
                break;//exit the while loop
            } else {//if the user is not done
                int position = getStateIndex(theStates, state);//find the state index
                if (position != -1) {//make sure it's a valid input
                    System.out.println("Bird: " + theStates[position][1]);//print out the bird
                    System.out.println("Flower: " + theStates[position][2]);//print out the flower
                    visitedStates.add(state);//add it to the list of visited states
                } else {
                    System.out.println("Invalid state entered");//bad input we don't print and don't store
                }
            }

        }

    }

    public static int getStateIndex(String theState[][], String state) {
        int position = -1;
        boolean found = false;
        for (int index = 0; index < theState.length && !found; index++) {
            if (theState[index][0].equalsIgnoreCase(state))
                position = index;
        }
        return position;
    }

}

Sample output: 样本输出:

    Enter a State or None to exit: 
    Idaho
    Bird: Peregrine Falcon
    Flower: Mock Orange
    Enter a State or None to exit: 
    Nevada
    Bird: Mountain Bluebird
    Flower: Sagebush
    Enter a State or None to exit: 
    None
    **** Thank you *****
    A summary report for each State, Bird, and Flower is: 
    [Idaho, Peregrine Falcon, Mock Orange]
    [Nevada, Mountain Bluebird, Sagebush]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM