Exceções punho casued pelo scanner de entrada

studentaccount4:

Eu estou tentando fazer programa de codificação / decodificação e eu estou encontrando todos os tipos de exceções aqui!

problemas que está surgindo causados ​​pelo único scanner múltipla / / s:

  • InputMismatchException | NumberFormatException (TENTATIVA 2)

  • NoSuchElementException (TENTATIVA 3)

Antes de atravessar gostaria de endereço que esta não é uma duplicata e eu olhei para cima vários problemas em StackOverFlow deste tipo e nenhum me ajudou realmente muito. Problemas similiar que eu olhei: link1 link2

Note-se que os resultados finais desejados são como os resultados da primeira tentativa, mas com alguma forma melhor tratamento de exceção mais limpo e scanners fechadas.

PRIMEIRA TENTATIVA

  • Agora este programa me dá os resultados desejados, mas o seu programação ruim ter dois scanners e um deles (scanner método de entrada) não está fechado:

    public static void main(String[] args) {
    Scanner sc=new Scanner (System.in);
    int choice = 0;
    do {
        System.out.println("This program to encode or decode a byte array " +
                "\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");
            //break; if i uncomment this the programm will work For Ever
        }
        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();
     }
    
     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 StackOverflow using ArrayList to store bytes is inefficient
    Scanner inScanner=new Scanner (System.in);
    
    ByteArrayOutputStream inArray= new ByteArrayOutputStream();
    
    System.out.println("enter a sequence of ints please! ");
    System.out.println("non-int will terminate the input!");
    
    while (inScanner.hasNext()) {
        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();
     }
    

SAÍDA DA PRIMEIRA TENTATIVA:

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.

SEGUNDA TENTATIVA

Então o que eu fiz depois de um colega de vocês sugessted para dar uma olhada neste problema ligação é a seguinte:

Agora eu não fechar o scanner de entrada e eu dei o método de entrada de um scanner como um parâmetro:

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 StackOverflow 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();
}

Se o fizer, não me dá os resultados desejados em tudo:

  • Depois de escolher uma para codificar e receba os codificado bytes I vai ficar preso para sempre no modo de codificação ea InputMismatchException | NumberFormatExceptioncláusula vai ficar ativado por isso não posso ter a chance de selecionar uma nova entrada!

    Este é um programa para codificar ou decodificar bytes baseado em RLE algoritmo (o_O) As opções são: 1: Prima 1 para entrar no modo de codificar 2: Pressione 2 para entrar no modo de decodificação 3: Pressione 3 para sair! 1 entrar no modo de codificar! digite uma seqüência de bytes por favor! não-int irá encerrar a entrada! 1 e entrada terminada! 1 da lista codificada é 1 Este é um programa para codificar ou decodificar bytes baseado em RLE algoritmo (o_O) As opções são: 1: Prima 1 para entrar no modo de codificar 2: Pressione 2 para entrar no modo de decodificação 3: Pressione 3 para sair! tipo inválido ou formato! entrar no modo de codificar! digite uma seqüência de bytes por favor! não-int irá encerrar a entrada!

  • NOTAS:

  • 1.commenting sc.close()na principal causada exatamente o mesmo erro que acima ..
  • 2. Que se deslocam do scanner acima principal e declaing-lo como uma variável estática global, fez a coisa exata como a faild acima dos resultados.

TENTATIVA TERCEIRO

agora eu deixei tanto do fechada cada scanner e isso ativou o NoSuchElementExceptionem Tomar principal uma olhada:

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 StackOverflow 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();
}

nesta tentativa i, pelo menos, pode saber o que está causando a NoSuchElementExceptionsaltar para cima e eu acho que é porque fechando um scanner irá fechar o fluxo de entrada para todo o código. (corrija-me se estou errado!)

SAÍDA PARA A tentativa terceira é:

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

SOLUÇÃO PARA DISCUTIR POR @Villat

Primeiro de todos os grandes graças a você o homem para ajudar e investir tempo e esforço. Agora, eu tenho pequena pergunta sobre estas linhas:

 if(sc.hasNextInt()) choice=sc.nextInt();
            else {
                sc.next();
                continue;
            }
            error = false;
  • Então deixe-me ver se eu entendi direito, essas linhas desempenhar um papel como uma precaução, e por favor me corrija se estou errado !, para evitar a exceção de avançar para cima direita.

Assim Não seria suficiente para escrever o seguinte amaragem os try-catchblocos porque NoSuchElementExceptionnão tem chance de surgir eo InputMismatchExceptionestá sendo tratada e prevenida pelo bloco mais:

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

Apenas para treinar purpouses se eu gostaria de lidar com esse erro por try-catchbloco que você considerá-lo limpo e imune a Exceções se eu escreveu assim: (deixando de lado o NumberFormatException)

-então Demonstrando a Handle variantda sua resposta seria como esse direito?

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

Fiz algumas alterações em seu código (e comentários removidos para torná-lo mais legível). Basicamente, eu só estou usando um Scanneragora, e eu não estou a avançar para as opções até que um sc.nextInt()aparece.

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();
}

Método de entrada:

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();
}

Acho que você gosta

Origin http://43.154.161.224:23101/article/api/json?id=313369&siteId=1
Recomendado
Clasificación