MrPencil
MrPencil

Reputation: 964

The string is getting the wrong value

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`
  }

Upvotes: 1

Views: 296

Answers (3)

Arcot Raj
Arcot Raj

Reputation: 1

        String newName = "111";
    Character number = newName.charAt(2); // here number is 1
    Character numberBefore = newName.charAt(1); // here numberBefore is 1

    if (Character.getNumericValue(numberBefore) > 0) {  // checking against numeric rather than ascii
        System.out.println("ASCII value of char " + (int) number); // ASCII code for '1' = 49
        String start = String.valueOf(number) + String.valueOf(number) + " " + number + number; // here start is `98 11`
        System.out.println(start);
    }
}

Upvotes: -1

kmanu
kmanu

Reputation: 44

yes this is because of associativity of +

you can try the below code also

String c1 =Character.toString(number);
String s =c1+c1+" "+c1+c1;

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503539

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);

Upvotes: 10

Related Questions