2017-10-17 86 views
-3

我試圖在java上做一個健壯的代碼,但它似乎沒有工作。我在尋找的是用戶輸入一個輸入,如果輸入不是必需的輸入,程序將檢查輸入,然後用戶可以選擇重新輸入適當的輸入,直到輸入與所需的輸入相匹配,或者乾脆退出。這是我到目前爲止。當我運行這段代碼時,除非用戶輸入了錯誤的輸入並且想要退出,否則一切運行良好。即使用戶重新輸入正確的輸入或退出,while循環也會繼續運行並不會停止。我該如何做這項工作?如何使用用戶輸入使健壯性發揮作用?

//question 
    System.out.println("Summer, Winter, Fall, or Spring"); 
    System.out.print("Which season is your favarite? "); 
    String favSeason = in.next(); 
    System.out.println(); 

    //Control the inputs by converting them to Upper Case 
    String favSeasonInput = favSeason.toUpperCase(); 

    //required answers of the question 
    String seasons = "SUMMER, WINTER, FALL, SPRING?"; 
    String quit = "QUIT!"; 

    boolean isSeasons = (favSeasonInput.equals(seasons.substring(0, 6)) || 
      favSeasonInput.equals(seasons.substring(8, 14)) || 
      favSeasonInput.equals(seasons.substring(16, 20)) || 
      favSeasonInput.equals(seasons.substring(22, 28))); 
    boolean isQuit = favSeasonInput.equals(quit.substring(0, 4)); 
    //inialize variables that will compute scores 
    int favSeasonScore = 0; 

    //if user enters an input otherthan seasons 
    while (!isSeasons){ 

     favSeason = in.next(); 

     if(isQuit){ 
      System.exit(0); 
     } 

    } 


    //Conditions to set up scores for seasons 
    if(favSeasonInput.equals(seasons.substring(0, 6))){ 
     favSeasonScore = 6; 
     System.out.println("Summer is " + favSeasonScore + " points"); 
    } 
    else if(favSeasonInput.equals(seasons.substring(8, 14))){ 
     favSeasonScore = 14; 
     System.out.println("Winter is " + favSeasonScore + " points"); 
    } 
    else if(favSeasonInput.equals(seasons.substring(16, 20))){ 
     favSeasonScore = 20; 
     System.out.println("Fall is " + favSeasonScore + " points"); 
    } 
    else if(favSeasonInput.equals(seasons.substring(22, 28))){ 
     favSeasonScore = 28; 
     System.out.println("Spring is " + favSeasonScore + " points"); 
    } 

    System.out.println(favSeasonScore); 
+2

不包含代碼作爲圖像粘貼在這裏 – Lokesh

+0

請在此處粘貼您的代碼並解釋n您正在收到什麼錯誤 –

+1

您現有的代碼有什麼問題? –

回答

0

問題是,當您讀取新輸入時,您不更新布爾變量的值;你甚至不會將它讀入同一個變量。

所以:

favSeason = in.next(); 

應該是:

favSeasonInput = in.next().toUpperCase(); 
isSeaons = ...; 
isQuit = ...; 

但是請注意,檢查有效的輸入的方式是可怕。這是非常低效的(抽出每個支票上的子字符串),但也非常脆弱(必須使這些索引正確),並且需要更改時必須在多個位置更新代碼。

你映射一個字符串轉換爲整數,所以使用地圖:

Map<String, Integer> seasonScores = new HashMap<>(); 
seasonScores.put("SPRING", 28); 
// Etc. 

那麼你isSeason變量變爲:

isSeason = seasonScores.keySet().containsKey(favSeasonInput); 

而且你的條件語句消失,成爲:

seasonScore = seasonScores.get(favSeasonInput);