简体   繁体   中英

How do you take inputted characters and output them a certain number of times?

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM