扫描程序在switch语句之间使用While循环时出现问题

时间:2018-10-30 05:27:32

标签: java while-loop switch-statement

我正在尝试使用while和switch语句来运行扫描器。而且我了解到,由于先前存储的值,扫描程序ID在后续运行中会引发错误。我已经尝试了使用if语句的替代方法并可以运行它。但是,我想知道如何解决这个问题:

import java.util.Scanner;
public class me {
public static void main(String[] args) {
    String gender;
    int boy, girl, counter;
    counter = 0;
    Scanner me = new Scanner(System.in);    
    while (counter == 0) {
        System.out.println("Please enter your gender");
        gender = me.nextLine();     
        switch(gender) {
        case "boy" : {
            System.out.println("Enter your age, please.");
            boy = me.nextInt();
            if (boy > 21 && boy < 60) {
                System.out.println("Please enter");
            }
            else {
                System.out.println("Sorry, you must be between 18 and 60");
            }
        }
        break;
        case "girl" : {
            System.out.println("Enter your age, please.");
            girl = me.nextInt();
            if (girl > 21 && girl < 60) {
                System.out.println("Please enter");
            }
            else {
                System.out.println("Sorry, you must be between 18 and 60");
            }
        }
        break;
        default : {
            System.out.println("Please enter a valid gender");
        }
        break;
        }
    }
    me.close();
}
}

0 个答案:

没有答案