我试过在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);
答案 0 :(得分:0)
问题是,当您阅读新输入时,您不会更新布尔变量的值;你甚至不把它读成同一个变量。
所以:
favSeason = in.next();
应该是:
favSeasonInput = in.next().toUpperCase();
isSeaons = ...;
isQuit = ...;
但请注意,这种检查有效输入的方式是糟糕。这是非常低效的(在每个检查中拉出子串),但也非常脆弱(您必须正确地获得这些索引),并且当您的需求发生变化时,您必须在多个位置更新代码。
您正在将字符串映射到整数,因此请使用Map:
Map<String, Integer> seasonScores = new HashMap<>();
seasonScores.put("SPRING", 28);
// Etc.
然后您的isSeason
变量变为:
isSeason = seasonScores.keySet().containsKey(favSeasonInput);
你的条件消失了,变成了:
seasonScore = seasonScores.get(favSeasonInput);