首先需要说明的问题: 什么是杨辉三角形?
如图所示:杨辉三角形由数字排列,基本的特点是两侧的数值均为1,其它位置的数值是基正上方的数值与其左上方的数值之和.
代码实现:
package test; import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner; public class Demo{public static void main(String[] args) throws Exception{ // scanner();
// redirectOutputStream();
// encode();
triangle();
} @SuppressWarnings("resource")
public static void scanner()
{
Scanner scanner = new Scanner(System.in);
System.out.println("请输入你的名字:");
String line = scanner.nextLine();
System.out.println(line);
} public static void redirectOutputStream(){
//重定向系统输出流
//D:\Users\Hoonick_Cheng\Desktop\stack.txt
try
{
PrintStream out = System.out;
String filePath = "D:"+ File.separator + "Users"+File.separator
+"Hoonick_Cheng"+File.separator+"Desktop"+File.separator+"log.txt";
PrintStream ps = new PrintStream(filePath);
System.setOut(ps);
int age = 18;
System.out.println("定义对象年龄为: " + age);
String sex = "男";
System.out.println("定义对象性别为: " + sex);
String info = "这是个" + sex + "孩子,已经" + age + "岁了!";
System.out.println("整合两个变量为: " + info);
System.setOut(out);
System.out.println("程序运行完毕,请查看日志文档!");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
} public static void encode(){
//数A与数B异或两次得到的还是A,可以用于简单的加密解密
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个英文字符串或解密字符串:");
String password = scanner.nextLine();
char[] charArray = password.toCharArray();
for (int i = 0; i < charArray.length; i++)
{
charArray[i] = (char) (charArray[i] ^ 20000);
} System.out.println("加密或解密的结果如下:");
System.err.println(new String(charArray));
} public static void triangle(){
int arr[][] = new int[10][];
for (int i = 0; i < arr.length; i++)
{
arr[i] = new int[i+1];
for (int j = 0; j <=i; j++)
{
if (i==0||j==0||j==i)
{
arr[i][j] = 1;//两侧的数值均为1
}else {
arr[i][j] = arr[i-1][j] + arr[i-1][j-1];//正上方的数值与其左上方的数值之和
}
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}
}
}