adding text after prompt for input

2.1k views Asked by At

I'm new to Java & I don't even know if what I'm trying to do is actually doable in cmd but I want to know if there's a way to ask the user for an input while displaying something at the right of the input, something like:

enter weight: _ kg

specifying the unit I want the weight in for example

here is the code sample I have so far

import java.util.*;

public class ScannerPrompt {

  public static void main(String[] args) {

    int[] listOfIntegers = new int[10];

    Scanner s = new Scanner(System.in);

    for (int i = 0; i < 10; i++) {
      System.out.print("Enter num: ");
      int num = s.nextInt();
      listOfIntegers[i] = num;
    }

  }
}
2

There are 2 answers

0
54l3d On BEST ANSWER

We can use \r in a tricky way:

import java.util.Scanner;

public class JavaApplication2 {
  public static void main(String[] args) {
        int i=0;
        Scanner s = new Scanner(System.in);
        System.out.print("Enter num: __kg\r");
        System.out.print("Enter num: ");
        i = s.nextInt();
        System.out.println("\n"+i);     
    }
}

How it works:

  • we print Enter num: __kg and \r to make cursor at the begining of the line
  • Now if we print something, it will overwrite the fist message because cursor is in fist position, so we overwrite with same letters but just the part that will make the cursor at the desired position. Hence we print Enter num:

Dont use println because it insert \n at the end, and dont test in an IDE but use the console of your system.

0
Reimeus On

You could use carriage return \r to relocate the cursor to the start of line

System.out.printf("%20skg\rEnter num: ", " ");