Error with Scanner when ordering an integer nextInt () and then a String nextLine ()

1

I'm asking for a string to insert into a file, if the file does not exist I think so and if it exists I rewrite it, it seems simple but for some reason it does not ask me to speak, the instruction is skipped. I do not understand anything because if I ask again a second time if he listens to me. I would like to know what is due and what solution there is.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class FicheroBytess {
    public static void main(String[] args)  {
        Scanner in = new Scanner(System.in);
        String cadena,nombreFich;



        System.out.println("Escribe el texto que va contener el fichero"); 
        cadena=in.nextLine();//leola linea compleata ylo guardo en un String
        System.out.println("Escribe el nombre del fichero");
        nombreFich=in.nextLine();//leo la linea completa y la guardo en un string
        File f = new File(nombreFich);// defino la ubicacion
        FileOutputStream fos; //declaro el stream
        try {
        if (!(f.exists())) {//si no existe el fichero
            System.out.println("No existe entonces lo creo");
                    fos = new FileOutputStream(nombreFich); //creo el fichero aqui tengo dudas   //flujo de salida de archivo   
                    char c[] =cadena.toCharArray();    //guardo el String en un array de caracteres
                    for (int i = 0; i < c.length; i++) { //recorro el array carcter por carcter
                        try {
                            fos.write((byte)c[i]);   //escribo cada posicion del caracter en el archivo conwrite
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }       

            System.out.println("archivo "+f+" creado");

        }           
                int opcion;
                do {//do while con un tres sale del programa
                    do {//perite un numero entre 1y 3
                        System.out.println("Existe y menu\n" //menu
                                + "1. Reescribir fichero\n"
                                + "2. Añadir al final\n"
                                + "3. Atras\n");
                    opcion = in.nextInt();//Elegimos opciondel menu


                    switch (opcion) {
                    case 1://como elijo uno
                        System.out.println("Escribe una cadena");//mensaje
                         cadena=in.nextLine();//IMPORTANTE  AQUI PASA DE LARGO!!!!! NO LO ENTIENDO!!!!
                         //cadena=in.nextLine();   //si lo repito una segunda vez si lo leee no lo entiendo!!!
                         fos = new FileOutputStream(nombreFich);

                         char c[] =cadena.toCharArray();//igual que el anterior
                            System.out.println(cadena);
                            System.out.println(cadena.length());
                            for (int i = 0; i < c.length; i++) {
                                try {
                                    fos.write((byte)c[i]);
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                        break;
                    case 2://aqui aun no he llegado
                        fos = new FileOutputStream(nombreFich,true);
                        break;

                    default:
                        break;
                    }
                    } while (opcion < 1 || opcion > 3);
                } while (opcion != 3);//







         } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

                in.close();
    }

}
    
asked by David Palanco 13.05.2018 в 12:09
source

1 answer

3

The bug is when it comes to collecting the entire variable opcion .

How to clean the input buffer in Java

  

When in a program data numéricos and data of type carácter or String are read in a program, we must bear in mind that when entering the data and pressing enter we are also introducing the intro in the input buffer.   That is, when in a program we enter a data and press the intro as the end of input, the intro character also passes to the input buffer.   Input buffer if you enter a 5: 5 \ n

     

In this situation, the instruction:

     

n = sc.nextInt();

     

Assign to n the value 5 but the intro remains in the buffer   Input buffer after reading the whole: \ n

     

If now it is requested that a string of characters be entered by keyboard:

     

System.out.print("Introduzca su nombre: ");
nombre = sc.nextLine(); //leer un String

     

The nextLine () method extracts all the characters from the input buffer until it reaches an intro and eliminates the intro from the buffer.   In this case, assign an empty string to the name variable and clean the intro. This causes that the program does not work correctly, since it does not stop so that the name is introduced.

Solution:

  

The input buffer should be cleaned if data of character type a > continuation of the reading of numerical data.

     

The simplest way to clean the input buffer in Java is to execute the instruction:

     

sc.nextLine();

opcion = Integer.parseInt(in.nextLine());//Elegimos opciondel menu

Doing this already should work properly for you.

P.d. We could also do this to better understand what we are doing.

opcion = in.nextInt();
in.nextLine(); 

Not the other way around ..

  

Source Java Scanner for data reading

    
answered by 13.05.2018 / 12:54
source