I am trying to build a string like 11 11
but I am facing problem I am getting for start
the following string 98 11
and not 11 11
.
How can I fix that?
I appreciate any help.
Character number = newName.charAt(2); //here number is 1
Character numberBefore = newName.charAt(1); //here numberBefore is 1
try (PrintWriter writer = new PrintWriter(path+File.separator+newName);
Scanner scanner = new Scanner(file)) {
boolean shouldPrint = false;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(numberBefore >0 ){
String start= number+number+" "+number+number; //here start is `98 11`
}
Yes, this is due to the associativity of +
.
This:
String start= number+number+" "+number+number;
is effectively:
String start = (((number + number) + " ") + number) + number;
So you're getting number + number
(which is performing numeric promotion to int
) and then string concatenation.
It sounds like you want:
String numberString = String.valueOf(number);
String start = numberString + numberString + " " + numberString + numberString;
Or alternatively:
String start = String.format("%0c%0c %0c%0c", number);
See more on this question at Stackoverflow