package project2;
import java.util.*;
public class Project2 {
public static void main(String[] args) {
String Name;
int age;
Scanner input = new Scanner(System.in);
System.out.print("Enter your age : ");
age = input.nextInt();
if (age>=16){
System.out.println("Your good to go");}
else if ((age>=1)&&(age<=15)){
System.out.println("Your not allowed to Procced");}
else{
System.out.println("Out of range");}
}
}
抱歉新手:/。所以,当我在&#34;输入你的年龄&#34;是节目
输入您的年龄:q
线程中的异常&#34; main&#34; java.util.InputMismatchException
在java.util.Scanner.throwFor(Scanner.java:909)
在java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
在project2.Project2.main(Project2.java:14)
Java结果:1
我想如果我输入任何显示的字母&#34;输入无效&#34;。谁能帮我? [抱歉坏英语]
答案 0 :(得分:1)
如果我输入任何显示的字母&#34;输入无效&#34;。任何人都可以帮助我吗?
抓住异常并打印消息,如下所示 -
try{
System.out.print("Enter your age : ");
age = input.nextInt();
}catch(RuntimeException ex){
System.out.println("Invalid input");
}
答案 1 :(得分:0)
你有没有问别人他的年龄,他告诉你:q
?这不是一个年龄而不是int
。
您获得了例外,因为nextInt
:
throws InputMismatchException
- 如果下一个令牌与之匹配 整数正则表达式,或超出范围
答案 2 :(得分:0)
在使用input.nextInt()
读取int之前,请检查input.hasNextInt()
,它将读取足够的内容以判断它是否为int(但留给nextInt读取;它不会搞砸什么)然后返回。
if(!input.hasNextInt())
System.out.println("Not an int");
else
{
int age = input.nextInt();
// other code here
}
答案 3 :(得分:0)
试试这个:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int age = 0;
boolean isContinue = true;
do {
try {
System.out.print("Enter your age : ");
String age1 = input.next();
age = Integer.parseInt(age1);
isContinue = false;
if (age >= 16) {
System.out.println("Your good to go");
} else if ((age >= 1) && (age <= 15)) {
System.out.println("Your not allowed to Procced");
} else {
System.out.println("Out of range");
}
} catch (NumberFormatException e) {
System.out.println("Not an valid age");
}
} while (isContinue);
System.out.println("other code");
}
答案 4 :(得分:0)
将输入作为字符串并检查它是否为数字
Scanner input = new Scanner(System.in);
System.out.print("Enter your age : ");
String rawAge = input.next();
try {
int age = Integer.parseInt(rawAge);
System.out.println("Age: " + age);
// Do something with age
} catch (NumberFormatException e) {
System.out.println("Invalid input for age");
}
答案 5 :(得分:0)
使用异常处理
import java.util.*;
public class crack
{
public static void main(String[] args)
{
String Age;
Scanner input = new Scanner(System.in);
System.out.print("Enter your age : ");
Age = input.nextLine();
try
{
int age = Integer.parseInt(Age);
if (age>=16)
{
System.out.println("Your good to go");
}
else if ((age>=1)&&(age<=15))
{
System.out.println("Your not allowed to Procced");
}
}
catch(NumberFormatException nFE)
{
System.out.println("out of range");}
}
}
}