重复该程序,直到用户使用数组键入none为止



我试图重复运行我的代码,直到用户键入none为止。当我键入州的名称时,我需要它使州花和州鸟一次,没有任何错误消息(再试一次(。但因为我写了for(int i=0; i<stateInfo.length; i++)行,它重复了49次"重试",并在数组中状态所在的第n行给出了答案。我只需要打印州花和州鸟就可以了。

//import Scanner, time.Duration, time.Instant
import java.util.Scanner;
import java.time.Duration;
import java.time.Instant;
public class StateFlowerBird {
/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    //Time counts starts
    Instant start = Instant.now();
    //greeting user
    greetings();
    //construct Scanner
    Scanner scannerIn = new Scanner(System.in);
    String state = "";
do {
    //2D Arrays with State, state flower, and state bird
    String[][] stateInfo = new String[][]{
    {"Alabama", "Camellia", "Yellowhammer"},
    {"Alaska", "Forget-me-not", "Willow Ptarmigan"},
    {"Arizona", "Saguaro cactus", "Cactus Wren"},
    {"Arkansas", "Apple blossom", "Mockingbird"},
    {"California", "Golden poppy", "California Valley Quail"},
    {"Colorado", "Rocky Mountain Columbine", "Lark Bunting"},
    {"Connecticut", "Mountain laurel", "Robin"},
    {"Delaware", "Peach blossom", "Blue Hen Chicken"},
    {"Florida", "Orange blossom", "Mockingbird"},
    {"Georgia", "Cherokee rose", "Brown Thrasher"},
    {"Hawaii", "Hibiscus", "Nene"},
    {"Idaho", "Syringa", "Mountain Bluebird"},
    {"Illinois", "Native violet", "Cardinal"},
    {"Indiana", "Peony", "Cardinal"},
    {"Iowa", "Wild rose", "Eastern Goldfinch"},
    {"Kansas", "Native sunflower", "Western Meadowlark"},
    {"Kentucky", "Goldenrod", "Cardinal"},
    {"Louisiana", "Magnolia", "Eastern Brown"},
    {"Maine", "Pine cone & tassle", "Chickadee"},
    {"Maryland", "Black Eyed Susan", "Baltimore Oriole"},
    {"Massachusettes", "Mayflower", "Chickadee"},
    {"Michigan", "Apple blossom", "Robin"},
    {"Minnesota", "Lady slipper", "Common Loon"},
    {"Mississippi", "Magnolia", "Mockingbird"},
    {"Missouri", "Hawthorn", "Bluebird"},
    {"Montana", "Bitterroot", "Western Meadowlark"},
    {"Nebraska", "Goldenrod", "Western Meadowlark"},
    {"Nevada", "Sagebrush", "Mountain Bluebird"},
    {"New Hampshire", "Purple lilac", "Purple Finch"},
    {"New Jersey", "Purple violet", "Eastern Goldfinch"},
    {"New Mexico", "yucca", "Roadrunner"},
    {"New York", "Rose", "Bluebird"},
    {"North Carolina", "Dogwood", "Cardinal"},
    {"North Dakota", "Wild prairie rose", "Western Meadowlark"},
    {"Ohio", "Scarlet carnation", "Cardinal"},
    {"Oklahoma", "Mistletoe", "Scissor-tailed"},
    {"Oregon", "Oregon Grape", "Western Meadowlark"},
    {"Pennsylvania", "Mountain laurel", "Ruffed Grouse"},
    {"Rhode Island", "Violet", "Rhode Island Red"},
    {"South Carolina", "Yellow jessamine", "Great Carolina Wren"},
    {"South Dakota", "Pasque flower", "Ring-necked Pheasant"},
    {"Tennesssee", "Purple iris", "Mockingbird"},
    {"Texas", "Texas Blue Bonnet", "Mockingbird"},
    {"Utah", "Sego lily", "American Seagull"},
    {"Vermont", "Red clover", "Hermit Thrush"},
    {"Virginia", "Dogwood", "Cardinal"},
    {"Washington", "Western rhododendron", "Willow Goldfinch"},
    {"West Virginia", "Rhododendron", "Cardinal"},
    {"Wisconsin", "Wood violet", "Robin"},
    {"Wyoming", "Indian paint brush", "Western Meadowlark"}}; 
    state = "";
    //Ask user to type the name of state or none
    System.out.println("nEnter a State or None to exit: " + state);
    state = scannerIn.nextLine();
    for(int stateNum = 0;stateNum<stateInfo.length;stateNum++){
        if(stateInfo[stateNum][0].equalsIgnoreCase(state)){
            System.out.println("Flower: " +stateInfo[stateNum][1]
                    + "nBird: " + stateInfo[stateNum][2]);
        }
        else if(!stateInfo[stateNum][0].equalsIgnoreCase(state)){
            errorMessage();
        }
    }
} while(!state.equalsIgnoreCase("None"));
    if (state.equalsIgnoreCase("None")){
        endStatement();
    }
    Instant end = Instant.now();
        System.out.println("Elapsed time in seconds was: " 
            + Duration.between(start, end).toNanos()/1_000_000_000.0 
            + " seconds.");
    System.out.println("**********************************");
    System.exit(0);
}

private static void greetings() {
        System.out.println("*****************************************************");
    System.out.println("***** Let's find out the state flower and bird! *****");
}
private static void endStatement() {
    System.out.println("n***** Thank you for playing! *****");
}
private static void errorMessage() {
    System.out.println("Invalid State. Try it again.");
}
}

在if条件中使用"break"。一旦找到匹配项,循环就会中断。

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
//import Scanner, time.Duration, time.Instant
import java.util.Scanner;
import java.time.Duration;
import java.time.Instant;
public class StateFlowerBird {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        //Time counts starts
        Instant start = Instant.now();
        //greeting user
        greetings();
        //construct Scanner
        Scanner scannerIn = new Scanner(System.in);
        String state = "";
        do {
            //2D Arrays with State, state flower, and state bird
            String[][] stateInfo = new String[][]{
                {"Alabama", "Camellia", "Yellowhammer"},
                {"Alaska", "Forget-me-not", "Willow Ptarmigan"},
                {"Arizona", "Saguaro cactus", "Cactus Wren"},
                {"Arkansas", "Apple blossom", "Mockingbird"},
                {"California", "Golden poppy", "California Valley Quail"},
                {"Colorado", "Rocky Mountain Columbine", "Lark Bunting"},
                {"Connecticut", "Mountain laurel", "Robin"},
                {"Delaware", "Peach blossom", "Blue Hen Chicken"},
                {"Florida", "Orange blossom", "Mockingbird"},
                {"Georgia", "Cherokee rose", "Brown Thrasher"},
                {"Hawaii", "Hibiscus", "Nene"},
                {"Idaho", "Syringa", "Mountain Bluebird"},
                {"Illinois", "Native violet", "Cardinal"},
                {"Indiana", "Peony", "Cardinal"},
                {"Iowa", "Wild rose", "Eastern Goldfinch"},
                {"Kansas", "Native sunflower", "Western Meadowlark"},
                {"Kentucky", "Goldenrod", "Cardinal"},
                {"Louisiana", "Magnolia", "Eastern Brown"},
                {"Maine", "Pine cone & tassle", "Chickadee"},
                {"Maryland", "Black Eyed Susan", "Baltimore Oriole"},
                {"Massachusettes", "Mayflower", "Chickadee"},
                {"Michigan", "Apple blossom", "Robin"},
                {"Minnesota", "Lady slipper", "Common Loon"},
                {"Mississippi", "Magnolia", "Mockingbird"},
                {"Missouri", "Hawthorn", "Bluebird"},
                {"Montana", "Bitterroot", "Western Meadowlark"},
                {"Nebraska", "Goldenrod", "Western Meadowlark"},
                {"Nevada", "Sagebrush", "Mountain Bluebird"},
                {"New Hampshire", "Purple lilac", "Purple Finch"},
                {"New Jersey", "Purple violet", "Eastern Goldfinch"},
                {"New Mexico", "yucca", "Roadrunner"},
                {"New York", "Rose", "Bluebird"},
                {"North Carolina", "Dogwood", "Cardinal"},
                {"North Dakota", "Wild prairie rose", "Western Meadowlark"},
                {"Ohio", "Scarlet carnation", "Cardinal"},
                {"Oklahoma", "Mistletoe", "Scissor-tailed"},
                {"Oregon", "Oregon Grape", "Western Meadowlark"},
                {"Pennsylvania", "Mountain laurel", "Ruffed Grouse"},
                {"Rhode Island", "Violet", "Rhode Island Red"},
                {"South Carolina", "Yellow jessamine", "Great Carolina Wren"},
                {"South Dakota", "Pasque flower", "Ring-necked Pheasant"},
                {"Tennesssee", "Purple iris", "Mockingbird"},
                {"Texas", "Texas Blue Bonnet", "Mockingbird"},
                {"Utah", "Sego lily", "American Seagull"},
                {"Vermont", "Red clover", "Hermit Thrush"},
                {"Virginia", "Dogwood", "Cardinal"},
                {"Washington", "Western rhododendron", "Willow Goldfinch"},
                {"West Virginia", "Rhododendron", "Cardinal"},
                {"Wisconsin", "Wood violet", "Robin"},
                {"Wyoming", "Indian paint brush", "Western Meadowlark"}};
            state = "";
            //Ask user to type the name of state or none
            System.out.println("nEnter a State or None to exit: " + state);
            state = scannerIn.nextLine();
            boolean flag = false;
            int index=0;
            for (int stateNum = 0; stateNum < stateInfo.length; stateNum++) {
                if (stateInfo[stateNum][0].equalsIgnoreCase(state)) {
                   index=stateNum; 
                   flag=true;
                } else if (!stateInfo[stateNum][0].equalsIgnoreCase(state)) {
                }
            }
            if (flag) {
                System.out.println("Flower: " + stateInfo[index][1]
                        + "nBird: " + stateInfo[index][2]);
            } else{
                errorMessage();
            }
        } while (!state.equalsIgnoreCase("None"));
        if (state.equalsIgnoreCase("None")) {
            endStatement();
        }
        Instant end = Instant.now();
        System.out.println("**********************************");
        System.exit(0);
    }
    private static void greetings() {
        System.out.println("*****************************************************");
        System.out.println("***** Let's find out the state flower and bird! *****");
    }
    private static void endStatement() {
        System.out.println("n***** Thank you for playing! *****");
    }
    private static void errorMessage() {
        System.out.println("Invalid State. Try it again.");
    }
}

我刚刚更改了您的循环,请查看此更改:

boolean flag = false;
            int index=0;
            for (int stateNum = 0; stateNum < stateInfo.length; stateNum++) {
                if (stateInfo[stateNum][0].equalsIgnoreCase(state)) {
                   index=stateNum; 
                   flag=true;
                } else if (!stateInfo[stateNum][0].equalsIgnoreCase(state)) {
                }
            }
            if (flag) {
                System.out.println("Flower: " + stateInfo[index][1]
                        + "nBird: " + stateInfo[index][2]);
            } else{
                errorMessage();
            }

在进入for循环检查状态之前,只需声明一个布尔值boolean stateFound=false;。当for循环中的条件为true(=找到状态(时,将其设置为true。删除else部分(带有错误消息(,并将if(!stateFound) {errorMessage();}放在循环之后。

Btw:为什么在do while循环的每个循环中都声明数组?

for(int stateNum = 0;stateNum<stateInfo.length;stateNum++){
        if(stateInfo[stateNum][0].equalsIgnoreCase(state)){
            System.out.println("Flower: " +stateInfo[stateNum][1]
                    + "nBird: " + stateInfo[stateNum][2]);
        }
        else if(!stateInfo[stateNum][0].equalsIgnoreCase(state)){
            errorMessage();//It Will execute for every non -matching items
        }
    }

在条件语句旁边使用break

文档链接:https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html

            if(stateInfo[stateNum][0].equalsIgnoreCase(state)){
                System.out.println("Flower: " +stateInfo[stateNum][1]
                        + "nBird: " + stateInfo[stateNum][2]);
                break;
            }
            else if(!stateInfo[stateNum][0].equalsIgnoreCase(state)){
                errorMessage();
                break;
            }

其次,您可以使用布尔值来检查结果显示基于标志的消息。

相关内容

最新更新