如何将输入的字符输出一定次数



我必须写一个程序,输入两个字符,并使用一个方法将它们x次打印出来。到目前为止,它将输出数字而不是字符。我该怎么修理它?

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

这是因为添加字符不是串联。请看这个问题:在Java中,两个字符相加的结果是int还是char?

你想要的是一个包含两个字符的字符串,可能最短的编辑是:

System.out.print("" + ch1 + ch2);

将该字符传递给Character.toString(char)以将其转换为String

System.out.print(Character.toString(ch1) + Character.toString(ch2));

相关内容

  • 没有找到相关文章

最新更新