I trying to figure out how to change the format of the variable that is entered by the user, all I found online is how to format already known values but nothing else really. the only thing is for sure is that the user is instructed to enter eight numbers only.
`System.out.print("Please enter your ID: ");
clientID = input.next();
System.out.println("Welcome " clientName "(Client ID: " clientID "), to yout invesment portfolio.");`
I tried to use the "String.format" method but I couldn't figure out how to edit the variable at a certain index.
CodePudding user response:
You can try this
clientID = String.format("%s-%s", clientID.substring(0, 4), clientID.substring(4));
Or this
clientID = clientID.substring(0, 4) "-" clientID.substring(4);
CodePudding user response:
You can also use some regex for this kind of tasks. In this simple case, it is probably a little bit overkill, but in general with regex, you are a lot more flexible.
public class MyClass {
public static void main(String args[]) {
String pattern = "^(\\d{4})(\\d{4})$";
String input = "12345678";
String parsedInput = input.replaceAll(pattern, "$1-$2");
System.out.println(parsedInput);
}
}
First you define your pattern. In this case we say that we have two blocks ^(...)(...)$
where each contains exactly 4 {4}
numbers \d
.
With the replaceAll
function, you then can rearrange these earlier defined blocks. They simply get numberd in order of appearance in the pattern. So $1
references the first block, $2
the second, and so on.
With that you can simply add the hypen in between the two blocks with $1-$2