我写了一段程序,目的是接收一段键盘的一段输入,如果是数字,执行下去,如果是字母,提出出错信息,然后再返回提示键盘输入的地方:
import java.util.*;
  public class wo {
  public static void main(String args[]) {
Scanner in=new Scanner(System.in);
System.out.println("输入数字:");
String s=in.nextLine();
//以上的语句收集输入值。 //以下检测输入的是否是整数
   try{ 
    int i = Integer.parseInt(s); 
    }catch(NumberFormatException nfe){ 
    System.out.println("违法数字格式!"); 
    }  }  
}
到这里,提示是出来了,但如何返回输入界面呢?

解决方案 »

  1.   

    import java.util.Scanner;public class Test {
        
        public static void main(String[] args) {
            Scanner in  = new Scanner(System.in);
            int num;
            while(true) {
                System.out.print("输入数字:");
                try {
                    num = in.nextInt();
                    break;
                }catch(Exception e) {
                    System.out.println("输入错误,请重新输入!");
                    // 这里一定要加上这么一句,否则会变成死循环
                      in.next();
                }
            }
            System.out.println("你输入的数字是:" + num);
        }
    }
      

  2.   


    import java.io.BufferedReader;
    import java.io.InputStreamReader;public class testNumber {
    public static void main(String[] args) {
    BufferedReader  in = new BufferedReader (new InputStreamReader(System.in));
            int num;
            while(true) {
    System.out.println("Please input a number : ");
    try {
    num = Integer.parseInt(in.readLine());
    break;
    } catch (Exception e) {
    System.out.println("输入错误,只能输入数字,请重新输入!");
    }
            } }
    }