2016-10-07 2 views
0

사용자가 none을 입력 할 때까지 반복적으로 코드를 실행하려고합니다. 그리고 국가 이름을 입력하면 오류 메시지없이 다시 한 번 상태 꽃과 주 조류를 만들 수 있습니다. 그러나 내가 for(int i=0; i<stateInfo.length; i++) 줄을 썼기 때문에, "try again"을 49 번 반복하고, 배열의 n 번째 줄에 답을 준다. 나는 국가 꽃과 주 (state)의 새만 인쇄하여 그것을 작동시켜야합니다.사용자가 배열을 사용하여 none을 입력 할 때까지 프로그램 반복

//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
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; 
      } 

둘째, 당신은 결과를 확인하기 위해 부울을 사용할 수 있습니다 플래그를 기반으로 메시지를 표시합니다. 내가 가진

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(); 
      } 
1

사용 '휴식'을하는 경우 상태. 일치가 발견되면 루프가 중단됩니다.

0

상태 점검을 위해 for-loop를 입력하기 전에 부울 값 boolean stateFound=false;을 선언하십시오. for 루프의 조건이 참일 때 (= 상태를 찾을 때) 이것을 true으로 설정하십시오. 루프 뒤에 else 부분 (오류 메시지와 함께)을 삭제하고 if(!stateFound) {errorMessage();}을 입력하십시오.

Btw : do while 루프의 모든 사이클에서 배열을 선언하는 이유는 무엇입니까?

관련 문제