-1

I am trying to create a method to introduce an int with NetBeans, but I have a problem when I run the method, the order of console messages is not correct, someone knows what the problem is:

public static void main(String[] args)
{
    Scanner teclado = new Scanner(System. in );
    int num;
    boolean error;

    public int introducirDatos()
    {
        do
        {
            error = false;
            try
            {
                System.out.println("Introduzca un número entero: ");
                num = Integer.valueOf(teclado.nextLine());

            }
            catch (NumberFormatException e)
            {
                System.err.println("Debe introducir un número y sin decimales, vuelve a intentarlo.\n");
                error = true;
            }
        } while (error == true);
        return num;
    }
}

Thanks.

  • You're not very clear about the problem that you're having. Specifically what output are you getting? What output were you expecting to get? – Kenster Dec 25 '15 at 18:11
  • The problem is the order in which System.out.print and System.err.print appear when I run the program, they appear mixed up. – joaquin_hel Dec 25 '15 at 18:47
  • What are you expecting and what do you get? – zedfoxus Dec 25 '15 at 20:14

1 Answers1

0

I believe you are running the code in an IDE - IntelliJ IDEA or Eclipse. The line System.out.println("Introduzca un número entero: "); prints to standard OUT, but System.err.println("Debe introdu... prints to standard ERROR. That's why the output gets messed up. Replace System.err with System.out for the messages being printed nicely one after another. BTW you haven't specified which language you are using. Is it Java? You might want to update the question tags.

vempo
  • 3,093
  • 1
  • 14
  • 16
  • Thank you very much!! That was exactly the problem I had. Can you tell me why it happens, why I can't use System.err? – joaquin_hel Dec 25 '15 at 18:31
  • In general, each program has 3 standard input-output (I/O) channels. You can read about them in https://en.wikipedia.org/wiki/Standard_streams. Stderr is usually separated from stdout so that they can be treated differently - for instance, all errors written into a file and all messages printed on screen. The problem happened because of how the IDE (Netbeans) treats the streams, and I assume your original program would run correctly in a terminal. I don't think you need to print to stderr, since your program runs in an interactive mode and you actually want to see the error messages. – vempo Dec 25 '15 at 18:57
  • You may also find the discussion in http://stackoverflow.com/questions/6121786/java-synchronizing-standard-out-and-standard-error useful – vempo Dec 25 '15 at 19:41