要求用户输入数字。如果输入错误,要求捕获错误,告知用户,给用户下一次输入的机会。直到正确为止,运行停止。(期间用户不输入任何东西,必须自动给下一次机会,且不限次数。)如果输入正确,告知用户正确,程序运行结束。
这个简单。我们想一下,用户输入的东西会是什么
字符串和数字
对,这两种组合。我们要求用户输入数字,则要调用nextInt方法。可是这个方法不能接受字符串,会产生异常,所以我们需要一个try
代码类似于这样:
import java.util.Scanner;
public class UsersInput
{
public static void main(String[] args)
{
try
{
Scanner in = new Scanner(System.in);
System.out.println("请输入数字:");
int usersInput = in.nextInt();
} catch (NumberFormatException e) {
}
}
}
到这里,一个基础的捕获异常的机制就有了,不过,我们还需要确定如何判断用户输入正确。即输入正确数字。这个很简单。try语句没执行catch分支那么用户就算是输入了正确的数字,并且要用while实现循环,这里我们这样:
import java.util.Scanner;
public class UsersInput
{
public static void main(String[] args)
{
while (true)
{
try
{
Scanner in = new Scanner(System.in);
System.out.println("请输入数字:");
int usersInput = in.nextInt();
System.out.println("输入正确!你输入了一个数字。程序结束");
break;//这里也可以换成System.exit(0);直接结束程序
} catch (NumberFormatException e) {
System.out.println("输入错误!输入的不是数字,请继续");
continue;//使用continue结束此次循环,开启下次循环
}
}
}
}
Scanner sc = new Scanner(System.in);
for(int i=1,i>0,i++){
System.out.println("输入数据:");
//多行输入
int n = sc.nextInt();
if(isInteger(n)){
//继续循环
}
}
public static boolean isInteger(String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
亲爱的提问者您好,我们很乐意您在CSDN找到问题的答案。
但是问答频道谢绝一切直接提问作业、求源代码等的行为,在此对您发出正式警告。
后续如果继续不加思考,直接提出作业问题,我们会限制您在问答频道的提问权益。
CSDN问答也鼓励用户通过举报功能来对这些行为进行监督反馈,共建问答频道良好的风气。
package usertransaction;
import java.util.Scanner;
public class UserTransaction {
public static void main(String[] args) {
int count=1;
while (count!=0)
{
try
{
Scanner in =new Scanner(System.in);
System.out.println("请输入数字:");
int usersInput= in.nextInt();
System.out.println("程序结束。");
count--;
}
catch(NumberFormatException e)
{
System.out.println("输入错误,请重新输入。");
}
catch(java.util.InputMismatchException e)
{
System.out.println("输入错误,请重新输入。");
}
}
}
}