2

I am trying to print out all the possibilities of a given string for a fixed length 3. Here is my program

import java.util.*;
import java.lang.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        String input = "abc";
        int i=0,j=0,k=0;
        for(i=0;i<3;i++){
            for(j=0;j<3;j++){
                for(k=0;k<3;k++){
                   System.out.println(input.charAt(i)+input.charAt(j)+input.charAt(k)); 
                }
            }
        }       
    }
}

But it prints the permutations of numbers in this format. But I intend to print aaa, aab, aac, bbb .. in that fashion.

291
292
293
292
293
294
293
294
295
292
293
294
293
294
295
294
295
296
293
294
295
294
295
296
295
296
297
gates
  • 4,465
  • 7
  • 32
  • 60

3 Answers3

2

charAt returns an integral type (actually a char which is a 16 bit unsigned integral type in Java). + is simply summing the values.

One way round that is to prefix the expression with an empty string literal: this forces Java to the interpret + as concatenation: "" + input.charAt(/*etc*/

In my opinion this is a flaw in Java permitting + to be used as a string concatenation operator.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

input.charAt(i) returns a char, which is an integer type. Therefore + performs int addition instead of concatenation of Strings.

Adding an empty String at the start of the expression will solve your problem :

System.out.println(""+input.charAt(i)+input.charAt(j)+input.charAt(k)); 
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Any idea how to make it generic? In the above code I explicitly wrote 3 loops, but in the run time if I ask the user to give the input string. Let's say he gave string of length 5, I can inject for loops dynamically right. Any solution? – gates Oct 20 '15 at 10:51
  • @gates You can use a recursive method. – Eran Oct 20 '15 at 10:55
  • can you provide me some resource in this regard? – gates Oct 20 '15 at 10:56
1

You used this line. That can solve your problem.

System.out.println(Character.toString(input.charAt(i))+Character.toString(input.charAt(j))+Character.toString(input.charAt(k)));

char a_char = input.charAt(0); // This is also return only a char
Shiladittya Chakraborty
  • 4,270
  • 8
  • 45
  • 94