62,614
社区成员
发帖
与我相关
我的任务
分享
import java.util.*;
class Test {
int i;
int sum=0;
Scanner c = new Scanner(System.in);
int f( ) {
do
{
System.out.println("请输入一个整数:");
i=c.nextInt( );
sum=sum+i;
} while (i!=999);
return sum;
}
}
class Sum
{
public static void main(String[] args)
{
Test t =new Test ();
int total = 0;
try
{ total = t.f( );
System.out.println("和等于"+total);
}
catch (InputMismatchException e )
{
System.out.println("你好,你输入的数值是非整数,请重新输入");
}
}
}
//check input
public static int userInput(){
Scanner console = new Scanner(System.in);
int key = 0;
try{
key = console.nextInt(16);
if(key > 15){//连续输入2个字符,会相加
System.out.println("输入错误,请重新输入: ");
key = userInput();
}
}catch(Exception e){
System.out.println("输入错误,请重新输入: ");
key = userInput();
}
return key;
}
public static void main(String[] args)
{
Test t =new Test ();
int total = 0;
while(true) {
try
{ total = t.f( );
System.out.println("和等于"+total);
break;
}
catch (InputMismatchException e )
{
System.out.println("你好,你输入的数值是非整数,请重新输入");
}
}
}