处理由输入扫描器引起的异常

handle Exceptions casued by input scanner

我正在尝试执行 encode/decode 程序,但我遇到了各种异常!

由 multiple/single scanner/s:

引起的弹出问题

在开始之前,我想说明这不是重复的,我已经在 Whosebug 上查找了多个此类问题,none 对我帮助很大。 我看过的类似问题: link2

请注意,希望的最终结果与第一次尝试的结果类似,但异常处理和关闭的扫描器在某种程度上更清晰。

第一次尝试

第一次尝试的结果:

This is a program to encode or decode bytes based on RLE ALgorithm
(o_O) Choices are: 
 1: Press 1 to enter the encode mode
 2: Press 2 to enter the decode mode
 3: Press 3 to Exit!
 1
 entering the encode mode!
 enter a sequence of bytes please! 
 non-int will terminate the input!
 1
 1
 3
 e
 input terminated!
 [1, 1, 3]
 the encoded list is [-1, 1, 2, 3]
 This is a program to encode or decode bytes based on RLE ALgorithm
 (o_O) Choices are: 
 1: Press 1 to enter the encode mode
 2: Press 2 to enter the decode mode
 3: Press 3 to Exit!
 At it goes forever without errors.

第二次尝试

所以在你们中的一个人建议看一下这个问题后我做了什么 link 是这样的:

现在我没有关闭输入扫描器,我给输入法一个扫描器作为参数:

public static void main(String[] args) {
    Scanner sc=new Scanner (System.in);
    int choice = 0;
    do {
        System.out.println("This is a program to encode or decode bytes based on RLE ALgorithm" +
                "\n (o_O) Choices are: " +
                "\n 1: Press 1 to enter the encode mode" +
                "\n 2: Press 2 to enter the decode mode" +
                "\n 3: Press 3 to Exit!");
        try {
            //it has to be parseInt because if you used sc.nextInt() the program will go nuts even with try catch.
            choice=Integer.parseInt(sc.next());
            //choice=sc.nextInt();
            /*Question: why when i use this with the existing try catch i the program work for ever but when i use Integer.parseInt(sc.nextLine())
             * the program would normally ask for another value?
             */
        } catch (InputMismatchException | NumberFormatException e) {
            System.out.println("invalid type or format!");
        } catch (NoSuchElementException e) {
            System.out.println("no such");//TODO SOLVE IT PLEASE ITS DRIVING ME CRAZYYYYYYYYYYY!!!!!!!
            break;
        }
        switch(choice){

        case 1 :
            System.out.println("entering the encode mode!");
            countAndEncode( input(sc) );
            break;
        case 2 :
            //countAndDecode( input(sc) );
            break;
        case 3 :
            System.out.println("exiting...");
            break;
        default :
            System.out.println("please enter a valid option and valid format!");
        }

    } while (choice!=3);
    sc.close();
}
/**
 * with this method user will be able to give the desired sequence of bytes. 
 * @return a byte array to be encoded.
 */
public static byte [] input(Scanner inScanner) {
    //arrayList because we dont know the size of the array its like StringBuilder
    //ArrayList<Byte> inArray = new ArrayList<Byte>(); 
    //according to Whosebug using ArrayList to store bytes is inefficient
    //Scanner   inScanner=new Scanner (System.in);

    ByteArrayOutputStream inArray= new ByteArrayOutputStream();

    System.out.println("enter a sequence of bytes please! ");
    System.out.println("non-int will terminate the input!");

    while (inScanner.hasNext()) {//TODO THIS MIGHT BE THE REASON FOR THE above "SUCH"
        byte i;
        try {
            i = inScanner.nextByte();   
            inArray.write(i);   
        } catch (InputMismatchException e) {
            System.out.println("input terminated!");
            break;
        }
    }
    System.out.println(Arrays.toString(inArray.toByteArray()));
    //inScanner.close();  dont close it because it cant be re-opened
    return inArray.toByteArray();
}

这样做根本没有给我想要的结果:

第三次尝试

现在我关闭了每个扫描仪,这激活了 main 中的 NoSuchElementException 看看:

public static void main(String[] args) {
    Scanner sc=new Scanner (System.in);
    int choice = 0;
    do {
        System.out.println("This is a program to encode or decode bytes based on RLE ALgorithm" +
                "\n (o_O) Choices are: " +
                "\n 1: Press 1 to enter the encode mode" +
                "\n 2: Press 2 to enter the decode mode" +
                "\n 3: Press 3 to Exit!");
        try {
            //it has to be parseInt because if you used sc.nextInt() the program will go nuts even with try catch.
            choice=Integer.parseInt(sc.next());
            //choice=sc.nextInt();
            /*Question: why when i use this with the existing try catch i the program work for ever but when i use Integer.parseInt(sc.nextLine())
             * the program would normally ask for another value?
             */
        } catch (InputMismatchException | NumberFormatException e) {
            System.out.println("invalid type or format!");
        } catch (NoSuchElementException e) {
            System.out.println("no such");//TODO SOLVE IT PLEASE ITS DRIVING ME CRAZYYYYYYYYYYY!!!!!!!
            break;
        }
        switch(choice){

        case 1 :
            System.out.println("entering the encode mode!");
            countAndEncode( input() );
            break;
        case 2 :
            //countAndDecode( input() );
            break;
        case 3 :
            System.out.println("exiting...");
            break;
        default :
            System.out.println("please enter a valid option and valid format!");
        }

    } while (choice!=3);
    sc.close();
}
/**
 * with this method user will be able to give the desired sequence of bytes. 
 * @return a byte array to be encoded.
 * @throws IOException 
 */
public static byte [] input() {
    //arrayList because we dont know the size of the array its like StringBuilder
    //ArrayList<Byte> inArray = new ArrayList<Byte>(); 
    //according to Whosebug using ArrayList to store bytes is inefficient
    Scanner inScanner=new Scanner (System.in);

    ByteArrayOutputStream inArray= new ByteArrayOutputStream();

    System.out.println("enter a sequence of bytes please! ");
    System.out.println("non-int will terminate the input!");

    while (inScanner.hasNext()) {//TODO THIS MIGHT BE THE REASON FOR THE above "SUCH"
        byte i;
        try {
            i = inScanner.nextByte();   
            inArray.write(i);   
        } catch (InputMismatchException e) {
            System.out.println("input terminated!");
            break;
        }
    }
    System.out.println(Arrays.toString(inArray.toByteArray()));
    inScanner.close(); 
    return inArray.toByteArray();
}

在这次尝试中,我至少可能知道是什么导致 NoSuchElementException 跳起来,我认为这是因为关闭一个扫描器将关闭整个代码的输入流。(如果我是,请纠正我错了!)

第三次尝试的结果是:

This is a program to encode or decode bytes based on RLE ALgorithm
(o_O) Choices are: 
 1: Press 1 to enter the encode mode
 2: Press 2 to enter the decode mode
 3: Press 3 to Exit!
 1
 entering the encode mode!
 enter a sequence of bytes please! 
 non-int will terminate the input!
-1
-1
 e
 input terminated!
 [-1, -1]
 the encoded list is [-1, -1, -1, -1]
 This is a program to encode or decode bytes based on RLE ALgorithm
 (o_O) Choices are: 
 1: Press 1 to enter the encode mode
 2: Press 2 to enter the decode mode
 3: Press 3 to Exit!
no such

@Villat 讨论的解决方案

首先非常感谢您的帮助和投入的时间和精力。 现在,我对这些行有一个小问题:

 if(sc.hasNextInt()) choice=sc.nextInt();
            else {
                sc.next();
                continue;
            }
            error = false;

所以写下面的 try-catch 块还不够吗,因为 NoSuchElementException 没有机会出现并且 InputMismatchException 正在被 else 块处理和阻止:

             while (error){
             if(sc.hasNextInt()) choice=sc.nextInt();
             else {
                 sc.next();
                 continue;
             }
             error = false;
             }

只是为了训练目的,如果我想通过 try-catch 块处理这个错误,如果我这样写,你会认为它干净并且不受异常影响吗:(放弃 NumberFormatException

-so 展示你的答案的 Handle variant 会是这样吗?

                while (error){
                try {
                    choice=sc.nextInt();
                    error = false;                
                } catch (InputMismatchException /*| NumberFormatException*/ e) {
                    error = false;
                    //System.out.println("invalid type or format!");    
                    sc.next();
                    continue;
                }
            }

我对您的代码进行了一些更改(并删除了注释以使其更具可读性)。基本上,我现在只使用一个 Scanner,并且在 sc.nextInt() 出现之前我不会进入选项。

public static void main(String[] args){
    Scanner sc=new Scanner (System.in);
    int choice = 0;
    do {
        System.out.println("This is a program to encode or decode bytes based on RLE ALgorithm" +
                "\n (o_O) Choices are: " +
                "\n 1: Press 1 to enter the encode mode" +
                "\n 2: Press 2 to enter the decode mode" +
                "\n 3: Press 3 to Exit!");
        boolean error = true;
        while (error){
            try {
                if(sc.hasNextInt()) choice=sc.nextInt();
                else {
                    sc.next();
                    continue;
                }
                error = false;
            } catch (InputMismatchException | NumberFormatException e) {
                System.out.println("invalid type or format!");
            } catch (NoSuchElementException e) {
                System.out.println("no such");
            }
        }
        switch(choice){

            case 1 :
                System.out.println("entering the encode mode!");
                System.out.println(input(sc));
                break;
            case 2 :
                //countAndDecode(input(sc));
                break;
            case 3 :
                System.out.println("exiting...");
                break;
            default :
                System.out.println("please enter a valid option and valid format!");
        }

    } while (choice!=3);
    sc.close();
}

输入法:

public static byte [] input(Scanner sc) {
    ByteArrayOutputStream inArray= new ByteArrayOutputStream();

    System.out.println("enter a sequence of bytes please! ");
    System.out.println("non-int will terminate the input!");

    while (sc.hasNext()) {
        byte i;
        try {
            i = sc.nextByte();
            inArray.write(i);
        } catch (InputMismatchException e) {
            System.out.println("input terminated!");
            break;
        }
    }
    System.out.println(Arrays.toString(inArray.toByteArray()));
    return inArray.toByteArray();
}