How to modify an existing System.out.println

0

If I run this code

public class main 
{
    public static void main(String[] args)
    {
        teste(20);
    }

    public static void teste(int maximo)
    {
        for(int i = 0; i < maximo; i++)
        {
            System.out.println(i + " de " + maximo);    
        }
    }
}

he will print this

0 de 30
1 de 30
2 de 30
3 de 30
4 de 30
5 de 30
6 de 30
7 de 30
8 de 30
9 de 30
10 de 30
11 de 30
12 de 30
13 de 30
14 de 30
15 de 30
16 de 30
17 de 30
18 de 30
19 de 30
20 de 30

But I would like instead of the line to repeat 20 times just modify the first one.

If you can tell me an API that can execute this would also help.

    
asked by anonymous 06.07.2015 / 18:49

2 answers

5

Use System.out.print() and escape character \r at the end of the text:

public static void teste(int maximo)
{
    for(int i = 0; i < maximo; i++)
    {
        System.out.print(i + " de " + maximo + "\r");    
    }
}

Instead of System.out.println() , which changes line after the display , System.out.print() always prints on the same line. The escape character \r causes the cursor to return to the beginning of the line.

The escape character is ignored by Eclipse console , so you have to run the program in a Windows command window .

As the code is, you will not be able to see anything, since the window will open and close almost immediately. To test enter the following changes:

public class App 
{
    public static void main(String[] args)
    {
        teste(4);
    }
    public static void teste(int maximo)
    {
        for(int i = 0; i < maximo; i++)
        {
            System.out.print(i + " de " + maximo + "\r");    
            try {
                //Espera meio segundo antes de prosseguir
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("\r\n");
        Scanner keyboard = new Scanner(System.in);
        //Espera que uma tecla seja premida antes de sair do programa
        String tecla = keyboard.next();     
    }
}
    
06.07.2015 / 18:58
1

If the intention is to show only the last result, then you can set a variable and execute System.out.print at the end:

private string resultadoFinal:

...

public static void teste(int maximo)
{
    for(int i = 0; i < maximo; i++)
    {
           resultadoFinal = i + " de " + maximo;
    }
}

System.out.print(resultadoFinal);

However if the execution is not within a loop and this code is illustrative only and still assuming that the results sent or output will be asynchronous, then it's like @Ramaral said, in Eclipse there will work using \r

    
06.07.2015 / 22:15