如何计算while循环中的各个用户选择

时间:2017-12-07 20:05:59

标签: java

我想知道如何计算用户在while循环中选择特定选项的次数。用户正在选择位置,我需要跟踪此位置的选择次数。没有使用阵列,最好的方法是什么?例如,我想跟踪每次while循环处理的时间,选择了多少伦敦,罗马或基韦斯特选项。

locationSelection = mainMenu(console);
while (locationSelection != 'Q') {
    if(locationSelection == 'A') { 
        locationSelectionString = "London, England.";
    }
    if (locationSelection == 'B') { 
        locationSelectionString = "Rome, Italy.";
    }
    if (locationSelection == 'C') { 
        locationSelectionString = "Key West, Florida.";
    }
    if (locationSelection == 'Q') {
        break;
    }

2 个答案:

答案 0 :(得分:0)

简单地宣布一个柜台。

int counter = 0;

然后在if语句中增加计数器。

int counterA = 0;
int counterB = 0;
int counterC = 0;
locationSelection = mainMenu(console);
while (locationSelection != 'Q') {
    if(locationSelection == 'A') { 
        locationSelectionString = "London, England.";
        counterA++;
    }
    if (locationSelection == 'B') { 
        locationSelectionString = "Rome, Italy.";
        counterB++;
    }
    if (locationSelection == 'C') { 
        locationSelectionString = "Key West, Florida.";
        counterC++;
    }
    if (locationSelection == 'Q') {
        break;
    }

答案 1 :(得分:0)

System.out.printf("Total London Vacations: %d", counterLondon);
System.out.printf("Total Rome Vacations: %d", counterRome );
System.out.printf("Total Key West Vacations: %d", counterKeyWest );