Home > database >  How to write in between characters in console using Scanner
How to write in between characters in console using Scanner

Time:12-18

I want to be able to write in between characters in the console using Scanner. The code Im using:

    Scanner sc = new Scanner(System.in);
    System.out.print("[customer ID: \t]");
    int id = sc.nextInt();

the current output would be:

[customer ID:   ]

and if i tried typing in between the brackets this would happen:

[customer ID:   ]123

is there any way to make the text appear in between the brackets? intended output:

[customer ID: 123]

CodePudding user response:

The answer is no. You need to hit the enter key for sc.nextInt() to read the input. Any output would be in the next line and not on the line where you enter the input.

System.out.print("[Customer ID: "   sc.nextInt()   "]";
24
[Customer ID: 524]

The closest I can think of this is something like this:

System.out.print("Customer ID: ");
int id = sc.nextInt();

which produce the output below:

Customer ID: 1234

CodePudding user response:

The answer to the question is no. Once the output is sent to the console (or some other output device) it's a done deal. You cannot retroactively modify the output that has already been consumed and modify it. You have to create a new output and send it to the output device. It is the same as printing a piece of paper and then make a correction directly to the paper from your program once it is printed out.

Alternatively, you can do something like this

Scanner sc = new Scanner(System.in);
System.out.print("Enter your customer ID: ")
int id = sc.nextInt();
System.out.print("[customer ID: "   id   "]");

Unfortunately, it is impossible to do what you asked.

  • Related