我试图在此上找到一些东西,但是在过去的一个小时的搜索中没有看到任何相关的东西。我试图在用户尝试输入数字而不是字符串时引发错误。
当用户输入字符串而不是int时,我发现了足够的资源来了解如何引发和出错,但是反之则无所作为。
我将快速编写一些代码
import java.util.Scanner;
public class ayylmao {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter your first name");
String AyyLmao = scan.nextLine();
System.out.println("Your first name is " + AyyLmao);
/*
Want it to say something like "Error: First character must be from the alphabet!" if the user tries to enter a number.
*/
}
}
如果这只是您感兴趣的第一个字符,则可以使用如下测试:
if (AyyLmao.charAt(0) >= '0' && AyyLmao.charAt(0) <= '9'){
/* complain here */
}
正如您显然已经发现的那样,对整个字符串进行测试将是:
try{
Integer.parseInt(AyyLmao);
/* complain here */
} catch(NumberFormatException ex){
/* this would be OK in your case */
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句