我正在尝试重复运行我的代码,直到用户输入无。当我输入状态的名称时,我需要它来制作状态花和状态鸟一次没有任何错误消息(再试一次)。但是因为我写了一行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.");
}
}
答案 0 :(得分:1)
在if条件中使用'break'。一旦找到匹配,循环就会中断。
答案 1 :(得分:0)
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;
}
其次,您可以使用布尔值来检查结果 根据标志显示消息。
答案 2 :(得分:0)
/*
* 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();
}
答案 3 :(得分:0)
在输入for循环以检查状态之前,只需声明一个布尔值boolean stateFound=false;
。当for循环中的条件为真(=找到状态)时,将此值设置为true
。删除else
部分(包含错误消息)并在循环后放置if(!stateFound) {errorMessage();}
。
顺便说一下:为什么要在do while
循环的每个循环中声明你的数组?