I was a mistake
I was a mistake

Reputation: 41

How do I replace the last output in the console with another output?

I'm working on Windows, and I want to be able to output multiple lines over the last output (which may as well contain multiple lines). How do I do this?

For example: A simple menu will pop up like

  1. alphabet
  2. numbers

The user inputs 1

Output:

a
b
c
d
e

Then the user inputs 2 again

I would want the console to erase the last blocks of output and replace them with the new output.

so

a
b
c
d
e

will be replaced by

1
2
3
4

in the console (they don't have the same number of lines.)

Upvotes: 2

Views: 153

Answers (1)

Jackson
Jackson

Reputation: 1223

Try this:

import java.io.IOException;
import java.util.Scanner;
public class Test3{
    public static void main(String args[]) throws IOException,InterruptedException{
        Scanner sc = new Scanner(System.in);
        int input = -2;
        int prevInput = -2;
        while(input != -1){
            System.out.println("\nMenu");
            System.out.println("---------");
            System.out.println("1: Alphabet");
            System.out.println("2: Numbers");
            System.out.print("Enter input : ");
            input = sc.nextInt();
            if(input!=prevInput)
                new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
            if(input == 1)
                System.out.println("a\nb\nc\nd\ne\n");
            else 
                System.out.println("1\n2\n3\n4");
            prevInput = input;
        }
    }
}

Upvotes: 1

Related Questions