在java编程中使用扫描器类以及使用数字的switch case语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18603177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:24:27  来源:igfitidea点击:

in java programming use a scanner class along with switch case statement using numbers

java

提问by user2744779

Can anybody tell me how to use "switch-case" for numbers along with scanner class, so that a number read from the keyboard should compare with switch cases given and final output should be printed?

谁能告诉我如何将“开关盒”用于数字和扫描仪类,以便从键盘读取的数字应与给定的开关盒进行比较并打印最终输出?

import java.util.Scanner;
public class Switchcase{
public static void main(String[] args) {

    int age;
    Scanner bhavya = new Scanner(System.in);
    System.out.println("enter your age:");
    age = bhavya.nextInt();
    switch (age) {
        case 1:
            System.out.println("you can crawl");
            break;
        case 2:
            System.out.println("you can talk");
            break;
        case 3:
            System.out.println("you can get in trouble");
            break;
        default:
            System.out.println("i dnt know how old you are");
            break;
    }
}

回答by Stephen C

Your program works ... apart from the fact that you are not dealing with the case where the user enters something that is not a valid integer.

您的程序可以正常工作......除了您没有处理用户输入的内容不是有效整数的情况之外。

You need to either use Scanner.hasNextInt()to test if the next token is an integer or catch and diagnose the exception that is thrown by Scanner.nextInt()when it can't read an int.

您需要使用Scanner.hasNextInt()来测试下一个标记是否为整数,或者捕获并诊断Scanner.nextInt()无法读取int.