0

I have to write a program that takes two inputted characters and print them out x times using a method. With what I have so far, it will output numbers instead of the characters. How can I fix it?

int length;
char ch1;
char ch2;

System.out.print("Enter a character: ");
ch1 = input.nextLine().charAt(0); //input refers to scanner.
System.out.print("Enter second character: ");
ch2 = input.nextLine().charAt(0); //input refers to scanner.
System.out.print("Enter the length of the line: ");
length = input.nextInt(); //input refers to how many times the characters ar$
draw_line(length, ch1, ch2);

//Method starts here.

public static void draw_line(int length, char ch1, char ch2){
    for (int i = 0; i < length; ++i){
        System.out.print(ch1 + ch2);
    }
}
Simon MᶜKenzie
  • 8,344
  • 13
  • 50
  • 77
Rara Uy
  • 3
  • 1

2 Answers2

1

This is because adding chars is not concatenation. Please see this question: In Java, is the result of the addition of two chars an int or a char?

What you want is a string containing two chars, probably the shortest edit is:

System.out.print("" + ch1 + ch2);
Community
  • 1
  • 1
sashkello
  • 17,306
  • 24
  • 81
  • 109
1

Pass the char to Character.toString(char) to convert it to a String.

System.out.print(Character.toString(ch1) + Character.toString(ch2));
Joe F
  • 4,174
  • 1
  • 14
  • 13