代码如下:
package example;
//JHTP Exercise 6.19: Square of Any Character
//by pandenghuang@163.com
/**(Displaying a Square of Any Character) Modify the method created in Exercise 6.18 to receive
a second parameter of type char called fillCharacter. Form the square using the char provided
as an argument. Thus, if side is 5 and fillCharacter is #, the method should display
#####
#####
#####
#####
#####
Use the following statement (in which input is a Scanner object) to read a character from the user
at the keyboard:
char fill = input.next().charAt(0);*/
import java.util.Scanner;
public class SquareofChar
{
public static void printSquare(int size,char c){
for (int i=0;i<size;i++){
for (int j=0;j<size;j++)
System.out.print(c);
System.out.println();
}
}
public static void main(String[] args)
{
int size=0;
char c=0;
Scanner input=new Scanner(System.in);
do {
System.out.print("请输入边长(整数,输入-1退出):");
size=input.nextInt();
if(size==-1)
System.out.print("已退出程序");
else
{
System.out.print("请输入字符:");
c=input.next().charAt(0);
printSquare(size,c);
}
}
while (size!=-1);
}
}
运行结果:
请输入边长(整数,输入-1退出):8
请输入字符:#
########
########
########
########
########
########
########
########
请输入边长(整数,输入-1退出):10
请输入字符:&
&&&&&&&&&&
&&&&&&&&&&
&&&&&&&&&&
&&&&&&&&&&
&&&&&&&&&&
&&&&&&&&&&
&&&&&&&&&&
&&&&&&&&&&
&&&&&&&&&&
&&&&&&&&&&
请输入边长(整数,输入-1退出):16
请输入字符:^
^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^