【问题标题】:Having difficulty getting user selection to output from a line in the array难以让用户选择从数组中的一行输出
【发布时间】:2015-03-01 22:05:21
【问题描述】:

我正在尝试开发一个程序,该程序接受用户输入并根据他们选择的状态输出相关的状态鸟和花。目前,如果您运行它,它将打印出每个状态和相关信息。但我试图让它只打印出 1 行。非常感谢任何帮助!

import java.util.Arrays;
import java.util.Scanner;

public class StateBirdAndFlower {

    private static String state = new String();
    private static final Scanner sc = new Scanner(System.in);
    private static final String[][] fsAndBs = {
        {"Alabama", "Flower: Camelia", "Bird: Northern flicker"},
        {"Alaska", "Flower: Forget-me-not", "Bird: Willow ptarmigan "},
        {"Arizona", "Flower: Saguaro cactus blossom", "Bird: Cactus wren "},
        {"Arkansas", "Flower: Apple blossom", "Bird: Northern mockingbird "},
        {"Califorina", "Flower: Califorina poppy", "Bird: California quail"},
        {"Colorado", "Flower: Rocky Mountian columbine", "Bird: Lark bunting"},
        {"Connecticut", "Flower: Mountain laurel ", "Bird: American robin"},
        {"Delaware", "Flower: Peach blossom", "Bird: Delaware Blue Hen "},
        {"Florida", "Flower: Orange blossom ", "Bird: Northern mockingbird "},
        {"Georgia", "Flower: Cherokee rose ", "Bird: Brown thrasher ", },
        {"Hawaii", "Flower: Hawaiian hibiscus ", "Bird: Nēnē or Hawaiian goose"},
        {"Idaho", "Flower: Syringa, mock orange ", "Bird: Mountain bluebird  "},
        {"Illinois", "Flower: Violet ", "Bird: Northern cardinal "},
        {"Indiana", "Flower: Peony ", "Bird: Northern cardinal "},
        {"Iowa ", "Flower: Wild prairie rose ", "Bird: Eastern goldfinch "},
        {"Kansas", "Flower: Sunflower", "Bird: Western meadowlark"},
        {"Kentucky", "Flower: Goldenrod ", "Bird: Northern cardinal"},
        {"Louisiana", "Flower: Magnolia ",  "Bird: Brown pelican "},
        {"Maine", "Flower: White pine cone and tassel ", "Bird: Black-capped "
            + "chickadee "},
        {"Maryland", "Flower: Black-eyed susan ", "Bird: Baltimore oriole"},
        {"Massachusetts", "Flower: Mayflower ", "Bird: Black-capped chickadee "},
        {"Michigan", "Flower: Apple blossom",  "Bird: American robin "},
        {"Minnesota", "Flower:Pink and white lady's slipper ","Bird: Common loon"},
        {"Mississippi", "Flower: Magnolia", "Bird: Northern mockingbird "},
        {"Missouri", "Flower: Hawthorn", "Bird: Eastern bluebird "},
        {"Montana", "Flower: Bitterroot ", "Bird: Western meadowlark "},
        {"Nebraska", "Flower: Goldenrod", "Bird: Western meadowlark"},
        {"Nevada", "Flower: Sagebrush ", "Bird: Mountain bluebird "},
        {"New Hampshire ", "Flower: Purple lilac ", "Bird: Purple finch "},
        {"New Jersey", "Flower: Violet ", "Bird: Eastern goldfinch "},
        {"New Mexico", "Flower: Yucca flower", "Bird: Roadrunner  "},
        {"New York", "Flower: Rose", "Bird: Eastern bluebird "},
        {"North Carolina", "Flower: Flowering dogwood", "Bird: Northern cardinal "},
        {"North Dakota", "Flower: Wild prairie rose ", "Bird: Western meadowlark "},
        {"Ohio", "Flower: carlet carnation ", "Bird Northern cardinal: "},
        {"Oklahoma", "Flower: Oklahoma rose ",  "Bird: Scissor-tailed flycatcher "},
        {"Oregon", "Flower: Oregon grape ", "Bird: Western meadowlark "},
        {"Pennsylvania", "Flower: Mountain laurel", "Bird: Ruffed grouse"},
        {"Rhode Island", "Flower: Violet", "Bird: Rhode Island Red "},
        {"South Carolina", "Flower: Yellow jessamine ","Bird: Carolina wren", },
        {"South Dakota ", "Flower: Pasque flower ", "Bird: Ring-necked pheasant"},
        {"Tennessee", "Flower: Iris", "Bird: Northern mockingbird ",},
        {"Texas", "Flower: Bluebonnet sp. ", "Bird: Northern mockingbird "},
        {"Utah", "Flower: Sego lily", "Bird: California gull "},
        {"Vermont", "Flower: Red clover ", "Bird: Hermit thrush"},
        {"Virginia", "Flower: American dogwood", "Bird: Northern cardinal"},
        {"Washington", "Flower: Coast rhododendron", "Bird: Willow goldfinch "},
        {"West Virginia", "Flower:Rhododendron", "Bird: Northern cardinal "},
        {"Wisconsin", "Flower: Wood violet ", "Bird: American robin "},
        {"Wyoming", "Flower: Indian paintbrush ", "Bird: Western meadowlark "}};

    public static void main(String[] args) {

        for(int rows = 0; rows < fsAndBs.length; rows++) {
            System.out.println("");

                for(int col = 0; col < fsAndBs[col].length; col++) {
                    System.out.println(fsAndBs[rows][col] + " ");

                }
            }



        do {
            System.out.println("Enter a State or None to Exit");
            state = sc.next();




        } while (!state.equalsIgnoreCase("none"));

        if (state.equalsIgnoreCase("none")) {
            System.out.println("goodbye");
            System.exit(0);
        }

    }

}

【问题讨论】:

    标签: java arrays string input


    【解决方案1】:

    在此处使用 String[][] 可能不是最简单的答案,因为您必须遍历整个数组才能获得所需的状态。

    但这是解决方案:

    private String[] getState(String input){
        for(String [] state: fsAndBs){
            if(state[0].equalsIgnoreCase(input){
                return state;
            }
        }
        // return null if input is not a valid state
        return null;
    }
    

    然后只需将String [] stateValues = getState(state) 添加到您的主目录。

    更多的 OO 解决方案如下(它更冗长,但为您提供了可以传递和用户轻松传递的 State 对象,以及比那些可怕的二维数组更好的可读性)。

         public class StateBirdAndFlower {
    
             private static class State {
    
                 private final String name;
                 private final String bird;
                 private final String flower;
    
                 State(String name, String bird, String flower) {
                     this.name = name;
                     this.bird = bird;
                     this.flower = flower;
                 }
    
                 public String getName() {
                     return name;
                 }
    
                 public String getBird() {
                     return bird;
                 }
    
                 public String getFlower() {
                     return flower;
                 }
             }
    
             private static String stateName = new String();
             private static final Scanner sc = new Scanner(System.in);
             private static Map<String, State> statesMap = new HashMap<String, State>();
    
             public static void main() {
                 setupMap();
                 // ... your other code ...
    
                 do{
                     System.out.println("Enter a State or None to Exit");
                     stateName = sc.next();
                     State state = statesMap.get(stateName.toLowerCase());
                     // ... do your thing with the state ...
                 } while (!stateName.equalsIgnoreCase("none")); 
    
                 // .. the rest of your code here 
             }
    
             private static void setupMap() {
                 // set up a map entry for each state
                 State ala = new State("Alabama","Camelia","Northern flicker");
                 statesMap.put(ala.getName().toLowerCase(), ala);
                 State alas = new State("Alaska","Forget-me-not","Willow ptarmigan");
                 statesMap.put(alas.getName().toLowerCase(), alas);
                 // ... etc ...
             }
         }
    

    【讨论】:

    • 如果你不介意那也是最有帮助的。我再次非常感谢!
    • @DavidCline 我已经为您更新了一个独立的面向对象解决方案的答案。另外,为状态变量名称道歉,我不是美国人,所以我不像你们那样知道三个字母的缩写。
    • 感谢您的帮助,但我仍然无法使其正常工作
    • @DavidCline 似乎是什么症状......我们最终会让它发挥作用。
    • 我终于找到了我的问题,我非常感谢您为我提供的努力和帮助!非常感谢
    【解决方案2】:

    我发现我做错了什么。不过还是谢谢大家的帮助

    /* 文件:StateBirdAndFlowerProgram。 * 作者:大卫·克莱恩 * 日期:2015 年 2 月 28 日 * 目的:获取用户输入并将其与数组进行比较以收集适当的数据以输出。 * 用户想退出时不输入。 */ 导入 java.util.Scanner;

    公共类 StateBirdAndFlowerProgram {

     public static void main(String args[]) {
    
          // Begin Scanner for user input later on
          Scanner input = new Scanner( System.in );
    
           //Begin array of information
          String[][] states={
                            {"Alabama", "Flower: Camelia", "Bird: Northern flicker"},
                            {"Alaska", "Flower: Forget-me-not", "Bird: Willow ptarmigan "},
                            {"Arizona", "Flower: Saguaro cactus blossom", "Bird: Cactus wren "},
                            {"Arkansas", "Flower: Apple blossom", "Bird: Northern mockingbird "},
                            {"Califorina", "Flower: Califorina poppy", "Bird: California quail"},
                            {"Colorado", "Flower: Rocky Mountian columbine", "Bird: Lark bunting"},
                            {"Connecticut", "Flower: Mountain laurel ", "Bird: American robin"},
                            {"Delaware", "Flower: Peach blossom", "Bird: Delaware Blue Hen "},
                            {"Florida", "Flower: Orange blossom ", "Bird: Northern mockingbird "},
                            {"Georgia", "Flower: Cherokee rose ", "Bird: Brown thrasher ", },
                            {"Hawaii", "Flower: Hawaiian hibiscus ", "Bird: Nēnē or Hawaiian goose"},
                            {"Idaho", "Flower: Syringa, mock orange ", "Bird: Mountain bluebird  "},
                            {"Illinois", "Flower: Violet ", "Bird: Northern cardinal "},
                            {"Indiana", "Flower: Peony ", "Bird: Northern cardinal "},
                            {"Iowa ", "Flower: Wild prairie rose ", "Bird: Eastern goldfinch "},
                            {"Kansas", "Flower: Sunflower", "Bird: Western meadowlark"},
                            {"Kentucky", "Flower: Goldenrod ", "Bird: Northern cardinal"},
                            {"Louisiana", "Flower: Magnolia ",  "Bird: Brown pelican "},
                            {"Maine", "Flower: White pine cone and tassel ", "Bird: Black-capped chickadee "},
                            {"Maryland", "Flower: Black-eyed susan ", "Bird: Baltimore oriole"},
                            {"Massachusetts", "Flower: Mayflower ", "Bird: Black-capped chickadee "},
                            {"Michigan", "Flower: Apple blossom",  "Bird: American robin "},
                            {"Minnesota", "Flower:Pink and white lady's slipper ","Bird: Common loon"},
                            {"Mississippi", "Flower: Magnolia", "Bird: Northern mockingbird "},
                            {"Missouri", "Flower: Hawthorn", "Bird: Eastern bluebird "},
                            {"Montana", "Flower: Bitterroot ", "Bird: Western meadowlark "},
                            {"Nebraska", "Flower: Goldenrod", "Bird: Western meadowlark"},
                            {"Nevada", "Flower: Sagebrush ", "Bird: Mountain bluebird "},
                            {"New Hampshire ", "Flower: Purple lilac ", "Bird: Purple finch "},
                            {"New Jersey", "Flower: Violet ", "Bird: Eastern goldfinch "},
                            {"New Mexico", "Flower: Yucca flower", "Bird: Roadrunner  "},
                            {"New York", "Flower: Rose", "Bird: Eastern bluebird "},
                            {"North Carolina", "Flower: Flowering dogwood", "Bird: Northern cardinal "},
                            {"North Dakota", "Flower: Wild prairie rose ", "Bird: Western meadowlark "},
                            {"Ohio", "Flower: carlet carnation ", "Bird Northern cardinal: "},
                            {"Oklahoma", "Flower: Oklahoma rose ",  "Bird: Scissor-tailed flycatcher "},
                            {"Oregon", "Flower: Oregon grape ", "Bird: Western meadowlark "},
                            {"Pennsylvania", "Flower: Mountain laurel", "Bird: Ruffed grouse"},
                            {"Rhode Island", "Flower: Violet", "Bird: Rhode Island Red "},
                            {"South Carolina", "Flower: Yellow jessamine ","Bird: Carolina wren", },
                            {"South Dakota ", "Flower: Pasque flower ", "Bird: Ring-necked pheasant"},
                            {"Tennessee", "Flower: Iris", "Bird: Northern mockingbird ",},
                            {"Texas", "Flower: Bluebonnet sp. ", "Bird: Northern mockingbird "},
                            {"Utah", "Flower: Sego lily", "Bird: California gull "},
                            {"Vermont", "Flower: Red clover ", "Bird: Hermit thrush"},
                            {"Virginia", "Flower: American dogwood", "Bird: Northern cardinal"},
                            {"Washington", "Flower: Coast rhododendron", "Bird: Willow goldfinch "},
                            {"West Virginia", "Flower:Rhododendron", "Bird: Northern cardinal "},
                            {"Wisconsin", "Flower: Wood violet ", "Bird: American robin "},
                            {"Wyoming", "Flower: Indian paintbrush ", "Bird: Western meadowlark "}};
          // While loop to search through array
          while(true) {
    
               // Request user input
               System.out.println("Enter a state: ");
               // Capture user input
               String stateName =input.nextLine();
               // exit statement
               if(stateName.equalsIgnoreCase("None"))
                    // Exit program
                    System.exit(0);
    
               else {
                    // For loop to search through array
                    for(int row=0,column=0;row<states.length;row++) {
                         // If statement for matching input string to array data
                         if(states[row][0].equalsIgnoreCase(stateName)) {
                              // Print bird information
                              System.out.println("Bird: " + states[row][column+1]);
                              // Print Flower information
                              System.out.println("Flower: " + states[row][column+2] + "\n");
    
                         } // end if
    
                    } // end for
    
               } // end else
    
          } // end while
    
     } // end main
    

    } // 结束类

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-22
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多