java,输入一个数n,输出n*n的矩阵(正方形).例如:输入5,输出5*5的正方形
1个回答
2016-11-03
展开全部
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class JuZhen {
public static String format(int source,int len){
String sourceString = source+"";
if (sourceString.length() >= len) {
return sourceString;
}else {
String space = "";
for (int i = 0; i < (len=sourceString.length()); i++) {
space+=" ";
}
return space+sourceString;
}
}
public static void main(String[] args) throws Exception{
System.out.println("请输入要输出的矩阵长度");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String numString = br.readLine();
br.close();
int num = 0;
try {
num = Integer.parseInt(numString);
} catch (Exception e) {
System.out.println("输入内容非数字");
}
if (num <= 0) {
System.out.println("输入数字需为正整数");
}
int len = Integer.toString(num*num).length();
for (int i = 1; i <= num; i++) {
for (int j = 0; j < num; j++) {
int source = i+(j*num);
String print = format(source, len);
if (j==0) {
System.out.print(print);
}else {
System.out.print(" "+print);
}
}
System.out.println();
}
}
}
输出如下:
请输入要输出的矩阵长度
5
1 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询