简体   繁体   English

打印用户输入/多维数组

[英]Printing User Input/Multidimensional Array

I apologize if this is a repeat question. 如果这是一个重复的问题,我深表歉意。 I'm not sure what to look for. 我不确定要寻找什么。

This is for an assignment so I would really like a push in the right direction versus just getting the answer. 这是一项任务,所以我真的希望朝着正确的方向前进,而不是仅仅得到答案。 The code is to repeatedly ask a user to enter a state name which returns the state bird and state flower. 该代码是反复要求用户输入州名称,该名称返回州鸟和州花。 Once the user has entered "None," a summary prints out that contains the state, bird, and flower of each state the user entered. 用户输入“无”后,将打印出摘要,其中包含用户输入的每种状态的州,鸟和花。 Currently, the summary only prints the information of the LAST state entered by the user. 当前,摘要仅打印用户输入的LAST状态信息。

I am sorry for the sloppy work. 很抱歉我的工作草率。 I'm only beginning to learn! 我才刚刚开始学习!

public class StateInformation {

    private String[][] stateInfo =  {
        {"Alabama", "Yellowhammer", "Camellia"},
        {"Alaska", "Willow Ptarmigan", "Alpine Forget-Me-Not"},
        {"Arizona" , "Cactus Wren", "Saguaro Cactus Blossom"},
        {"Arkansas", "Northern Mockingbird", "Apple Blossom"},
        {"California", "California Quail", "California Poppy"},
        {"Colorado", "Lark Bunting", "Rocky Mountain Columbine"},
        {"Connecticut", "American Robin", "Mountain Laurel"},
        {"Delaware", "Blue Hen Chicken", "Peach Blossom"},
        {"Florida", "Northern Mockingbird", "Orange Blossom"},
        {"Georgia", "Brown Thrasher", "Cherokee Rose"},
        {"Hawaii", "Nene", "{Pua Aloalo"},
        {"Idaho", "Mountain Bluebird", "Syringa"},
        {"Illinois", "Greater Prairie-Chicken", "Violet"},
        {"Indiana", "Northern Cardinal", "Peony"},
        {"Iowa", "Eastern Goldfinch", "Wild Rose"},
        {"Kansas", "Weatern Meadowlark", "Wild Native Sunflower"},
        {"Kentucky", "Northern Cardinal", "Goldenrod"},
        {"Louisana", "Brown Pelican", "Louisana Iris"},
        {"Maine", "Black-Capped Chickadee", "White Pine Cone and Tassel"},
        {"Maryland", "Baltimore Oriole", "Black-Eyed Susan"},
        {"Massachusetts", "Black-Capped Chickadee", "Mayflower"},
        {"Michigan", "American Robin", "Apple Blossom"},
        {"Minnesota", "Common Loon", "Pink and White Lady Slipper"},
        {"Mississippi", "Northern Mockingbird", "Magnolia"},
        {"Missouri", "Eastern Bluebird", "White Hawthorn Blossom"},
        {"Montana", "Western Meadowlark", "Bitterroot"},
        {"Nebraska", "Western Meadowlark", "Goldenrod"},
        {"Neveda", "Mountain Bluebird", "Sagebrush"},
        {"New Hampshire", "Purple Finch", "Pink Lady's Slipper"},
        {"New Jersey", "Eastern Goldfinch", "Violet"},
        {"New Mexico", "Greater Roadrunner", "Yucca"},
        {"New York", "Eastern Bluebird", "Rose"},
        {"North Carolina", "Northern Cardinal", "Dogwood"},
        {"North Dakota", "Western Meadowlark", "Wild Prairie Rose"},
        {"Ohio", "Northern Cardinal", "White Trillium"},
        {"Oklahoma", "Scissor-Tailed Flycatcher", "Mistletoe"},
        {"Oregon", "Western Meadowlark", "Oregon Grape"},
        {"Pennslyvania", "Ruffed Grouse", "Mountain Laurel"},
        {"Rhode Island", "Rhode Island Red Chicken", "Violet"},
        {"South Carolina", "Carolina Wren", "Yellow Jessamine"},
        {"South Dakota", "Ring-necked Pheasant", "American Pasque"},
        {"Tennessee", "Northern Mockingbird", "Passion Flower"},
        {"Texas", "Northern Mockingbird", "Ennis"},
        {"Utah", "California Gull", "Sego Lily"},
        {"Vermont", "Hermit Thrush", "Red Clover"},
        {"Virginia", "Northern Cardinal", "American Dogwood"},
        {"Washington", "Willow Goldfinch", "Coast Rhododendron"},
        {"West Virginia", "Northern Cardinal", "Rhododendron"},
        {"Wisconsin", "American Robin", "Wood Violet"},
        {"Wyoming", "Western Meadowlark", "Indian Paintbrush"},
    };//End array initialization

    public StateInformation() {
    }

    public String[][] getStateInfo(){
       return stateInfo;
    }

    public void setState(String[][] state) {
        this.stateInfo = stateInfo;
    }
}
//End of Class

Here is the second class: 这是第二堂课:

//Second Class
import java.util.Scanner;

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

        StateInformation states = new StateInformation();   
        String [][] state = states.getStateInfo();  

        //Inserting scanner & variable. 
        Scanner scanner = new Scanner(System.in);

        while(true) {
            //Prompt the user to input a state name.  
            System.out.println("Please enter a state or None to exit: ");
            //Read the state entered by user, including leading/trailing white spaces.
            String stateInfo = scanner.nextLine();

            //If loop to end if None is entered.
            if (stateInfo.equalsIgnoreCase("None")) {
                break;
            } else {
                int position = getStatePosition(state, stateInfo);

                if (position != -1) {
                    System.out.println("Bird: " 
                                    + getBird(position, state) 
                                    +'\n' + "Flower: " 
                                    + getFlower(position, state) + '\n');
                }

                if ((scanner.nextLine().equals("None"))) {
                        System.out.println("***** Thank you! *****" + '\n' 
                            + "A summary report for each State, Bird, and Flower is: "
                            + '\n' + getState(position, state)+ ", "
                            + getBird(position, state) + ", "+ getFlower(position, state)
                            + '\n' + "Please visit our site again!");
                }//end if loop for printing bird and flower of state entered by user.
            }//End else loop
        }//end if loop
    }//end while loop


    private static int getStatePosition(String state[][], String stateInfo) {
        for (int i = 0; i < state.length; i++) {
            if (stateInfo.equalsIgnoreCase(state[i][0])) {
                return i;
            }
        }
        return -1;
    }

    //Creates the position of the state name into [0]
    private static String getState(int position, String [][] state) {
        return state[position][0];  
    }

    //Creates the position of the state bird into [1].
    private static String getBird(int position, String [][] state) {
        return state[position][1];
    }

    //Creates the position of the state bird into [2]
    private static String getFlower(int position, String [][] state) {
        return state[position][2];
    }
}

To get a summary of activity, you must store each state in a collection. 要获得活动摘要,必须将每个状态存储在一个集合中。 Here a Set is used to avoid duplicates. 这里使用Set来避免重复。
Example code showing each state stored in a Set, then iterating the Set follows: 示例代码显示了存储在Set中的每个状态,然后迭代Set:

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

    StateInformation states = new StateInformation();
    String[][] state = states.getStateInfo();
    // Inserting scanner & variable.
    Scanner scanner = new Scanner(System.in);
    Set<Integer> positions = new HashSet<Integer>();

    while (true) {
        // Prompt the user to input a state name.
        System.out.println("Please enter a state or None to exit: ");
        // Read the state entered by user, including leading/trailing white
        // spaces.
        String stateInfo = scanner.nextLine();

        // If loop to end if None is entered.
        if (stateInfo.equalsIgnoreCase("None")) {
            System.out.println(
                    "***** Thank you! *****" + '\n' + "A summary report for each State, Bird, and Flower is: \n");

            for (Integer p : positions) {
                System.out.println(getState(p, state) + ", " + getBird(p, state) + ", " + getFlower(p, state)
                                + '\n');
            }
            System.out.println("Please visit our site again!");
            break;
        } else {
            int position = getStatePosition(state, stateInfo);
            if (position != -1) {
                positions.add(position);
                System.out.println("New size=" + positions.size());
                System.out.println("Bird: " + getBird(position, state) + '\n' + "Flower: "
                        + getFlower(position, state) + '\n');
            }
        }
    }
}// end while loop

With sample output: 带有示例输出:

***** Thank you! *****
A summary report for each State, Bird, and Flower is: 

Alaska, Willow Ptarmigan, Alpine Forget-Me-Not

California, California Quail, California Poppy

Florida, Northern Mockingbird, Orange Blossom

Please visit our site again!

You don't seem to be too far off. 您似乎相距不远。 You're able to write out the info for each state, as requested, right - so all you're missing is a summary of those at the end? 您可以按照要求写出每个州的信息,对-所以您所缺少的只是最后的摘要?

What you need then is some kind of data-structure to let you store info about which states the user has asked about. 然后,您需要的是某种数据结构,以使您可以存储有关用户询问哪些状态的信息。 All you need to store for each question then, is a number - namely the index of that state. 然后,您需要为每个问题存储的只是一个数字-即该状态的索引。 If you are able to store all of those in a list, then at the end, you can simply loop over that list, and print out the relevant info for each of them. 如果您能够将所有这些存储在列表中,那么最后,您可以简单地遍历该列表,并打印出每个列表的相关信息。

Since a regular array like String[] will not be resizable, you'll probably want to use something like an ArrayList<Integer> instead. 由于像String[]这样的常规数组将无法调整大小,因此您可能想要使用ArrayList<Integer>类的东西。 Use that to store a new line of information in each time a user requests info about a new state. 每次用户请求有关新状态的信息时,使用该存储新的信息行。

Note: This assumes you want a log of what the user has asked for; 注意:这是假设您要记录用户的要求; if you don't want repetitions of the same states when the user has in fact asked for the same state several times, you can use some implementation of Dictionary instead, which will allow only a single instance of each state to be included in the final list. 如果当用户实际上多次要求相同状态时,如果您不希望重复相同状态,则可以改用Dictionary的某种实现,该实现只允许将每个状态的单个实例包含在最终状态中。清单。

Hope this was enough info to help you along... 希望这是足够的信息可以帮助您...

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

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