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

时间:2013-04-17 23:52:14

标签: java loops methods user-input void

我必须编写一个程序,它接受两个输入的字符并使用方法将它们打印出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);
    }
}

2 个答案:

答案 0 :(得分:1)

这是因为添加字符不是连接。请看这个问题:In Java, is the result of the addition of two chars an int or a char?

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

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

答案 1 :(得分:1)

将char传递给Character.toString(char),将其转换为String

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