java.util.InputMismatchException are ScannerInt


Good post this because even though I have solved it so that it looks good I do not understand why it gives me. I hope you can help me, I have the following code.

 package com.example.ejercicio1;

import java.util.Scanner;

class Ejercicio1 {
    int edad;
    String nombre, apellidos;
    Scanner teclado;
public void inicializar() {
    teclado=new Scanner(;
    System.out.println("Ingrese nombre:");;

    System.out.println("Ingrese sus apellidos");;

    System.out.println("Ingrese edad:");
    edad = teclado.nextInt();


public void imprimir(){
    System.out.println("El usuario se llama " + nombre + " " + apellidos);

public void esMayor(){
    if(edad > 18){
        System.out.println("El usuario  es mayor de edad");
    }else {
        System.out.println("No cumple la edad mínima");

public static void main(String[] args) {
    Ejercicio1 ejercicio1;

    ejercicio1 = new Ejercicio1();


And I get the following error Enter name: David Enter your last names Sales marin Enter age:


Exception in thread "main" java.util.InputMismatchException at   java.util.Scanner.throwFor ( at ( at   java.util.Scanner.nextInt ( at   java.util.Scanner.nextInt ( at   com.example.exercise1.Exercise1.initialize ( at   com.example.ejercicio1.Ejercicio1.main (

But if I change line 19 and 18 and put it on surnames, it's fine with me ... someone who knows why.


asked by DavidVentas 30.11.2018 в 11:34

1 answer


It gives you a MismatchException because when you use a getNext() instead of a getNextLine() you are not collecting in the entry the \n and therefore when you try to do the getNextInt() you are analyzing the string " \ n35 "instead of the number 35.

answered by 30.11.2018 / 11:52