【程序31】题目:将一个数组逆序输出。
public class Demo1 {
public static void main(String[] args) {
int[] array = { 1, 2, 3 , 4, 5, 6 ,7, 8 };
System.out.println("原数组输出:");
for (int i = 0; i <=array.length-1; i++){
System.out.print(array[i]+" ");
}
System.out.println();
System.out.println("原数组逆序输出");
for (int i = array.length-1; i >=0; i--){
System.out.print(array[i]+" ");
}
}
}
【运行结果】
原数组输出:
1 2 3 4 5 6 7 8
原数组逆序输出
8 7 6 5 4 3 2 1
【程序32】题目:取一个整数a从右端开始的4~7位。
public class Demo1 {
public static void main(String[] args) {
int a=0;
long b=12345678;
//a=(int) Math.floor(b % Math.pow(10,7)/Math.pow(10, 3));
//System.out.println(a);
String str = String.valueOf(b);
int len = str.length();
int beginIndex = len-7;
int endIndex =len-4+1;
String sub = str.substring(beginIndex, endIndex);
System.out.println(sub);
}
}
【运行结果】
2345
【程序33】题目:打印出杨辉三角形(要求打印出10行如下图)
import java.util.Scanner;
public class Demo1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[][] a=new int[n][n];
for(int i=0;i<n;i++){
a[i][0]=1;
a[i][i]=1;
}
for(int i=2;i<n;i++){
for(int j=1;j<i;j++){
a[i][j]=a[i-1][j-1]+a[i-1][j];
}
}
for(int i=0;i<n;i++){
for(int j=0;j<=i;j++){
System.out.printf(" %-3d", a[i][j]);
}
System.out.println();
}
}
}
【运行结果】
10
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
public class lianxi33 {
public static void main(String[] args) {
int[][] a = new int[10][10];
for (int i = 0; i < 10; i++) {
a[i][i] = 1;
a[i][0] = 1;
}
for (int i = 2; i < 10; i++) {
for (int j = 1; j < i; j++) {
a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
}
}
for (int i = 0; i < 10; i++) {
for (int k = 0; k < 2 * (10 - i) - 1; k++) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
//System.out.print(a[i][j] + " ");
System.out.printf( " %-3d",a[i][j] );
}
System.out.println();
}
}
}
【运行结果】
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1