写一个根据输入整数求和的程序,如果输入999则程序求和后结束,如果输入小数,则显示“输入数字格式不对,请重新输入”。下面的程序不能实现重新输入,请问该怎么修改: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("你好,你输入的数值是非整数,请重新输入");
 }
 
 

}

解决方案 »

  1.   


        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("你好,你输入的数值是非整数,请重新输入");
                      }
                }
                 
        } 
      

  2.   

    楼上方法可行!
    也可以把输入写成一个方法,捕获异常,递归调用改方法
    //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;
    }
      

  3.   

    楼主 你没看到 你catch语句里只有打印一句话:你输入的数值是非整数,请重新输入 吗?
    你自己要在后面在写个输入的方法呀 
    要不然捕获异常后打印一句话就停止了的