Loop with lector.hasNextInt ();

0

Given this code in the second iteration when an erroneous value is entered, the program loops without re-reading a value. I have tried to use "lector.nextLine ();" under "tipusValor = lector.hasNextInt ();", but then the reader is activated "numeroEscollit = lector.nextInt ();" after entering the values "a" and then "1".

The question is: Can you tell me how I can do a reading for each iteration and that it is detected if a value is of type int and if it falls within the established range?

Thanks in advance

import java.util.Scanner;
public class EjercicioWhile {
//Declarem constants
private static final int VALOR_MINIM = 1, VALOR_MAXIM = 20;

public static void main (String[] args) {
    Scanner lector = new Scanner(System.in);
    //Definim variables.
    boolean numeroCorrecte = false, tipusValor = true;
    int numeroEscollit = 0;

    //Demanem número.
    System.out.print("Aquest programa mostra els múltiples d'un número determinat.");
    while (!numeroCorrecte){
        System.out.println("\nEscriu un número entre 1 i 20: ");
        tipusValor = lector.hasNextInt();
        lector.nextLine();
        if (tipusValor){
             //Valor de tipus int.
            numeroEscollit= lector.nextInt();

            if ((numeroEscollit < VALOR_MINIM)||(numeroEscollit > VALOR_MAXIM)){
                //No s'ha introduit un número correcte. 
            }else{
                //Número correcte
                numeroCorrecte = true;
                System.out.println("TR: Numero correcte"); 
            }

        }else if (!numeroCorrecte){
            System.out.println("TR: Missatge d'error");
        }                            
    }

    System.out.println("TR: Hem sortit del bucle");
    
asked by Zuxis 26.10.2018 в 20:05
source

0 answers