如果第一个输入是字符,则打印大小写,如果输入是数字,则抛出异常。 [英] If the first input is character then print the case, if the input is number then throw exception.

查看:141
本文介绍了如果第一个输入是字符,则打印大小写,如果输入是数字,则抛出异常。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在java中编写代码来检查用户的第一个输入是否是字符然后打印大小写,如果输入是数字然后抛出异常。



我的尝试:



how to write a code in java to check if the first input by the user is character then print the case, if the input is number then throw exception.

What I have tried:

import java.util.Scanner;
import java.util.InputMismatchException;
public class Practice {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        try {
            System.out.print("Enter input: ");
      		String input=s.next();
            System.out.println("You entered "+s );
        } catch (InputMismatchException e) {
            System.out.println("You have entered invalid data");
        }
    }
}

推荐答案

您正在编写正常代码,但是为此工作你需要一个条件,

You are writing the normal code, however for this to work you need a condition,
// Integer.valueOf() is also going to throw exception. 
try {
   // your code
   if(!Integer.valueOf(input)) {
       throw new Exception("Number is not allowed.");
   } else {
       // Always true, because input[0] is always a character
   }
} catch (Exception e) {
   // What to do here?
}



但是,如果你的意思是字母数字,只用字母表进行测试(字母表不是唯一的字符,数字也是如此)。


However, if you meant a alphanumeric, to be tested with only an alphabet (alphabets are not the only characters, numbers too).

if(Character.isLetter(input[0])) {
   // Now this is a condition to check if that is a alphabet or not.
}



java是否有一个int.tryparse,它不会为坏数据抛出异常? - 堆栈溢出 [ ^ ]


这篇关于如果第一个输入是字符,则打印大小写,如果输入是数字,则抛出异常。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆