JAVA第四课:方法,数组

1. 方法/函数

方法:完成特定功能的代码块
格式:
	修饰符 返回值类型 方法名(参数类型 参数名1, 参数类型 参数名2…) {
		方法体;
		return 返回值;
	}

修饰符:public static
返回值类型:功能最终的值的数据类型
方法名:是为了方便调用而起的一个名字
参数:
	形式参数:用于接受实际参数的变量
	private static int max(int i, int j)
	上述代码中 i,j 便是属于形式参数。
	
	实际参数:实际参与运算的数据
	int mx = max(1,2);
	int mn = min(a,b);
	上述代码中 1,2,a,b 便是属于形式参数。

方法体:完成特定功能的代码
return 返回值:通过return把结果返回给调用者

我们虽然知道了方法的格式,那么我们该如何写一个方法呢?
两个明确:
	A:返回值类型
		结果的数据类型
	B:参数列表
		有几个参数参加,并且每个参数的数据类型是什么

方法的执行特点:
	不调用不执行。

有明确返回值的方法的调用:
	A:单独调用,没有意义。
	B:输出调用,不是很好,
	  因为我们可能需要针对结果还要进行其他的操作。
	C:赋值调用,推荐方式。
	
方法的注意事项:
	A:方法不调用不执行
	B:方法与方法是平级关系,不能嵌套定义
	C:方法定义的时候参数之间用逗号隔开
	D:方法调用的时候不用再传递数据类型
		可以传递变量,也可以常量。就是不能加数据类型
	E:如果方法有明确的返回值,一定要有return带回一个值
package test;

public class Test1 {
//  main --- alt + / --- enter
	public static void main(String[] args) {
		int mn = min(1, 2);
		System.out.println("mn = "+mn);

		int mx = max(1, 2);
		System.out.println("mx = "+mx);
	}
// 最大值函数
	private static int max(int i, int j) {
		return i > j ? i:j;
	}
// 最小值函数
	private static int min(int i, int j) {
		return i < j ? i:j;
	}
}

求两个数据之和的案例

	A:没有说数据的类型,默认int类型。
	B:求两个数据的和
	  		说明有两个参数参加,并且默认都是int类型
	C:两个int类型相加的结果是什么类型呢?
			是int类型,所以返回值类型这里是int类型
package test;

import java.util.Scanner;

public class Test2 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("input:");
		
		int a = sc.nextInt();
		int b = sc.nextInt();
		int ans = sum(a,b);
		System.out.println("sum = "+ans);
	}

// 两个数求和函数
	private static int sum(int a, int b) {
		return a+b;
	}
}

2. 方法重载

概述:
	在同一个类中,允许存在一个以上的同名方法,
	只要它们的参数个数或者参数类型不同即可。
特点:
	(1)与返回值类型无关,只看方法名和参数列表
	(2)在调用时,jvm/虚拟机通过参数列表的不同来区分同名方法
package test;
import java.util.Scanner;

public class Test3 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int a=1, b=2, c=3;
		double d = 3.14, e=3.1415;
		System.out.println("sum = "+sum(a,b));
		System.out.println("sum = "+sum(a,b,c));
		System.out.println("sum = "+sum(d, e));
	}
// 函数重载:同名函数,参数不同
	private static double sum(double a, double b) {
		return a+b;
	}
	private static int sum(int a, int b, int c) {
		return a+b+c;
	}
	private static int sum(int a, int b) {
		return a+b;
	}
}

B2137 判决素数个数

B2137 判决素数个数
X X X Y Y Y 之间的素数个数(包括 X X X Y Y Y)。

输入格式:两个整数 X X X Y Y Y 1 ≤ X , Y ≤ 1.1 × 1 0 6 1 \le X,Y \le 1.1 \times 10^6 1X,Y1.1×106)。
输出格式:输出一个整数,表示 X , Y X, Y X,Y 之间的素数个数(包括 X X X Y Y Y)。

样例输入:1 100
样例输出:25

package test;
import java.util.Scanner;

public class Test5 {
// B2137 判决素数个数
	public static void main(String[] args) {
		System.out.println("input:");
		Scanner sc = new Scanner(System.in);
		int x = sc.nextInt();
		int y = sc.nextInt();
		if(x > y) {
			int t = x; x= y; y=t;
		}
		int cnt = 0;	// x<=y
		for(int i=x; i<=y; i++) {
			if(isPrime(i)) cnt ++;
		}
		System.out.println(cnt);
	}
	private static boolean isPrime(int n) {
		for(int i=2; i<=n/i; i++) {
			if(n%i==0) return false;
		}
		return n > 1;
	}
}

P5723 【深基4.例13】质数口袋

P5723 【深基4.例13】质数口袋
小 A 有一个质数口袋,里面可以装各个质数。他从 2 2 2 开始,依次判断各个自然数是不是质数,如果是质数就会把这个数字装入口袋。

口袋的负载量就是口袋里的所有数字之和。

但是口袋的承重量有限,装的质数的和不能超过 L L L。给出 L L L,请问口袋里能装下几个质数?将这些质数从小往大输出,然后输出最多能装下的质数的个数,数字之间用换行隔开。

输入格式:一行一个正整数 L L L
输出格式:将这些质数从小往大输出,然后输出最多能装下的质数个数,所有数字之间有一空行。

样例输入 #1:100
样例输出 #1:

2
3
5
7
11
13
17
19
23
9

样例输入 #2:5
样例输出 #2:

2
3
2

样例输入 #3:11
样例输出 #3:

2
3
5
3

数据保证, 1 ≤ L ≤ 10 5 1 \le L \le {10}^5 1L105

package test;
import java.util.Scanner;

public class Test4 {
// P5723【深基4.例13】质数口袋
	public static void main(String[] args) {
		System.out.println("input:");
		Scanner sc = new Scanner(System.in);
		int L = sc.nextInt(), cnt=0;
		for(int i=2; i<=L; i++) { // 1e5 
			if(isPrime(i) && i<=L) { // O(sqrt(n))
				System.out.println(i);
				L -= i;
				cnt ++;
			}
		}
		System.out.println(cnt);
	}
// isPrime(int n):判断 n是不是素数
	private static boolean isPrime(int n) { // O(n)
//		n --- [2, n-1] --- [2, sqrt(n)]
//		97 --- [2, 96] --- [2, sqrt(96)]
//		n = a*b, a<=b.  ===> a^2 = b^2 = n
		for(int i=2; i<=n/i; i++) {
			if(n%i==0) return false;
		}
		return n > 1;
	}
}

3. 数组

数组概念
	数组是存储同一种数据类型多个元素的集合,也可以看成是一个容器。
	数组既可以存储基本数据类型,也可以存储引用数据类型。
	数组的每个元素都有编号,从0开始,最大编号是数组的长度-1。
	
数组的定义格式
	格式1:数据类型[] 数组名;
	格式2:数据类型 数组名[];
	注意:这两种定义做完了,数组中是没有元素值的。          	        

如何对数组的元素进行初始化呢?

数组初始化概述:
	Java中的数组必须先初始化,然后才能使用。
	所谓初始化:就是为数组中的数组元素分配内存空间,并为每个数组元素赋值。
数组的初始化方式
	动态初始化:初始化时只指定数组长度,由系统为数组分配初始值。
	静态初始化:初始化时指定每个数组元素的初始值,由系统决定数组长度。
	
	动态初始化:初始化时只指定数组长度,由系统为数组分配初始值。
	格式:数据类型[] 数组名 = new 数据类型[数组长度];
	数组长度其实就是数组中元素的个数。
	举例:
		int[] arr = new int[3];
	解释:定义了一个int类型的数组,这个数组中可以存放3个int类型的值。
	
	静态初始化:初始化时指定每个数组元素的初始值,由系统决定数组长度。
	格式:数据类型[] 数组名 = new 数据类型[]{元素1,元素2,…};
	举例:
		int[] arr = new int[]{1,2,3};
	解释:定义了一个int类型的数组,这个数组中可以存放3个int类型的值,并且值分别是1,2,3。
	其实这种写法还有一个简化的写法
		int[] arr = {1,2,3};
	
	Java 程序在运行时,需要在内存中的分配空间。
	为了提高运算效率,就对空间进行了不同区域的划分,
	因为每一片区域都有特定的处理数据方式和内存管理方式。
		栈		 存储局部变量
		堆 		 存储new出来的东西
		方法区	 (面向对象部分讲)
		本地方法区 (和系统相关)
		寄存器	 (给CPU使用)

数组索引越界ArrayIndexOutOfBoundsException
访问到了数组中的不存在的索引时发生。
空指针异常NullPointerException
数组引用没有指向实体,却在操作实体中的元素时。

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		int[] arr = new int [10];
		try {
			arr[10] = 11;
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		int[] b = null;
		try {
			b[10] = 11;
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
}

4. 数组与函数方法练习

(1)数组遍历(依次输出数组中的每一个元素)
(2)数组获取最值(获取数组中的最大值最小值)
(3)数组元素逆序 (就是把元素对调)
(4)数组查表法(根据键盘录入索引,查找对应星期)
(5)数组元素查找(查找指定元素第一次在数组中出现的索引)
(6)数组排序和二分查找(数组高级)

(1)数组遍历(依次输出数组中的每一个元素)

import java.util.Scanner;

class Test{
	public static void main(String[] args) {
		int[] arr = new int[]{1,2,3,4,5,6,7,8,9,0};
		//int[] arr = {1,2,3,4,5,6,7,8,9,0};
		for(int i=0; i<10; i++){
			System.out.println(arr[i]);
		}	
	}
}

(2)数组获取最值(获取数组中的最大值最小值)

import java.util.Scanner;

class Test{
	public static void main(String[] args) {
		int[] arr = new int[]{1,2,3,4,5,6,7,8,9,0};
		//int[] arr = {1,2,3,4,5,6,7,8,9,0};
		int max = arr[0];
		int min = arr[0];
		for(int i=0; i<10; i++){
			if(max<arr[i]) max = arr[i];
			if(min>arr[i]) min = arr[i];
		}
		System.out.println("max="+max+" min="+min);	
	}
}

(3)数组元素逆序 (就是把元素对调)

import java.util.Scanner;
import java.util.Collections;
import java.util.ArrayList;

class Test{
	public static void main(String[] args) {
		int[] arr1 = {1,2,3,4,5,6,7,8,9,0};
		int[] arr2 = {1,2,3,4,5,6,7,8,9,0};
		int[] arr3 = {1,2,3,4,5,6,7,8,9,0};
		
		show(arrayReverse1(arr1));
		show(arrayReverse2(arr2));
		show(arrayReverse3(arr3));
	}

	public static int[] arrayReverse1(int[] arr){
		//方式一:依次交换前后的值
		int temp = 0;
		int length = arr.length;
		for(int i=0; i<=length/2; i++){
			temp = arr[i];
			arr[i] = arr[length-i-1];
			arr[length-i-1] = temp;
		}
		return arr;
	}

	public static int[] arrayReverse2(int[] arr){
		//方式二:使用新的数组
		int length = arr.length;
		int[] arr2 = new int[length];
		for(int i=0; i<length; i++){
			arr2[i] = arr[length-i-1];
		}
		return arr2;
	}

	public static int[] arrayReverse3(int[] arr){
		//方式三:使用Collections.reverse(arraylist)方法
		int length = arr.length;
		ArrayList arraylist = new ArrayList();
		for (int i = 0; i < length; i++) {
            arraylist.add(arr[i]); //存放元素
        }
		Collections.reverse(arraylist); 
		for (int i = 0; i < length; i++) {
            arr[i] = (int) arraylist.get(i);
        }
		return arr;
	}

	//打印结果
	public static void show(int[] arr){
		int length = arr.length;
		for(int i=0; i<length; i++){
			System.out.print(arr[i]+" ");
		}
		System.out.println();
	}
}


(4)数组查表法(根据键盘录入索引,查找对应星期)

import java.util.Scanner;

class Test{
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入一个数字1~7:");
		int num = sc.nextInt();
		System.out.println(getWeek(num));
	}

	public static String getWeek(int x){
		String[] week= {"输入错误","星期一","星期二","星期三","星期四","星期五","星期六","星期日"};
		return week[x];
	}
}

(5)数组元素查找(查找指定元素第一次在数组中出现的索引)

import java.util.Scanner;

class Test{
	public static void main(String[] args) {
		String[] arr = {"a","b","c","d","e","f","g","h","i"};
		String str = "c";
		int index = getIndex(arr,str);
		System.out.println(index);
	}

	public static int getIndex(String[] arr, String str){
		for(int i=0; i<arr.length; i++)
			if(str == arr[i]) return i;
		return -1;
	}
}
import java.util.Scanner;

public class Test {
	// (5)数组元素查找(查找指定元素第一次在数组中出现的索引)
	public static void main(String[] args) {
		System.out.println("Input : ");
		Scanner sc = new Scanner(System.in);
		int[] arr = new int[10];
		for(int i=0; i<10; i++) {
			arr[i] = sc.nextInt();
		}
		int x = sc.nextInt();
		int index = find(arr, x);
		System.out.println("index = "+index);
	}
	// 查找指定元素第一次在数组中出现的索引,未找到返回 -1.
	private static int find(int[] arr, int x) {
		for(int i=0; i<arr.length; i++)
			if(arr[i]==x) return i;
		return -1;
	}
}

(6)数组排序和二分查找(数组高级)

public class Test {
//	(6)数组排序和二分查找(数组高级)
	public static void main(String[] args) {
		int[] arr = {9,5,6,7,8,2,0,4,3,1};
//		bubbleSort(arr);
//		bubbleSort2(arr, 0, arr.length-1);
//		bubbleSort(arr, 1,7); // [1,7]
//		selectSort(arr, 1,7);
		selectSort(arr, 0, arr.length-1);
		print(arr);
		int x = 3;
		int index1 = find(arr, x);
		int index2 = binSearch(arr, x);
		System.out.println("index1 = "+index1);
		System.out.println("index2 = "+index2);
	}
	// 二分查找:没有找到返回-1.
	// [l,r] = [l,mid-1] + mid + [mid+1, r]
	private static int binSearch(int[] arr, int x) {
		int l=0, r=arr.length-1, ans=0;
		while(l<=r) {
			int mid = (l+r)/2;
			if(arr[mid] >= x) {
				r = mid-1; ans=mid;
			}else {
				l = mid+1;
			}
		}
		if(arr[ans]!=x) ans=-1;
		return ans;
	}
	private static int find(int[] arr, int x) {
		for(int i=0; i<arr.length; i++)
			if(arr[i]==x) return i;
		return -1;
	}
	// 选择排序:每次选择最小的放在最前面  排序区间 [l,r]
	private static void selectSort(int[] arr, int l, int r) {
		for(int i=l; i<=r; i++) {
			int k = i; // 当前最小值所在位置
			for(int j=i+1; j<=r; j++) {
				if(arr[j] < arr[k]) k=j; // 更新最小值所在位置
			}
			int temp = arr[k]; arr[k]=arr[i]; arr[i]=temp;
		}
	}
// 冒泡排序:每次比较两个相邻元素,不合法就交换 排序区间 全部元素
	private static void bubbleSort(int[] arr) {
		for(int i=0; i<arr.length; i++)
			for(int j=0; j<arr.length-1-i; j++)
				if(arr[j] > arr[j+1]) {
					int temp = arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp;
				}
	}
	//  排序区间 [l,r]
	private static void bubbleSort(int[] arr, int l, int r) {
		for(int i=l; i<=r; i++)
			for(int j=l; j<=l+r-1-i; j++)
				if(arr[j] > arr[j+1]) {
					int temp = arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp;
				}
	}
	private static void bubbleSort2(int[] arr,int l,int r) {// 从后向前
		for(int i=r; i>=l; i--) {
			for(int j=l; j<i; j++) {
				if(arr[j] > arr[j+1]) {
					int temp = arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp;
				}
			}
			print(arr); // 输出每轮排序后的答案
		}
	}	
	// 输出
	private static void print(int[] arr) {
		for(int i=0; i<arr.length; i++)
			System.out.print(arr[i]+" ");
		System.out.println();
	}
}
import java.util.Arrays;

class Test{
	public static void main(String[] args) {
		int[] arr = {1,2,3,4,5,6,7,8,9,0};
		Arrays.sort(arr,0,arr.length);//排序
		for(int i=0; i<arr.length; i++){
			System.out.print(arr[i]+" ");
		}
		System.out.println();

		int[] arr2 = {1,2,3,4,5,6,7,8,9,0};
		sort(arr2,0,arr2.length);//排序
		for(int num:arr2){
			System.out.print(num + " ");
		}
		System.out.println();

		//二分查找: arr是已经排序好的
		int[] arr3 = {1,2,3,4,5,6,7,8,9,0};
		Arrays.sort(arr3,0,arr3.length);
		for(int num:arr3){
			System.out.print(num + " ");
		}
		System.out.println();
		int num = 9;
		int index = BinSearch(arr3,num);
		System.out.println(index);

	}

	//选择排序
	public static int[] sort(int[] arr, int a, int b){
		for(int i=a; i<b; i++){
			for(int j=i+1; j<b; j++){
				if(arr[i] > arr[j]){
					int temp = arr[i];
					arr[i] = arr[j];
					arr[j] = temp;
				}
			}
		}
		return arr;
	}

	//二分查找: arr是已经排序好的
	public static int BinSearch(int[] arr, int a){
		int low = 0;
		int hight = arr.length;
		int mid = 0;
		
		while(low <= hight){
			mid = (low+hight)/2;
			if(a < arr[mid]){
				hight = mid-1;
			}else if(a > arr[mid]){
				low = mid+1;
			}else{
				return mid;
			}
		}
		return 0;
	}
}

5. 二维数组

二维数组定义格式

格式1
	数据类型[][] 变量名 = new 数据类型[m][n];
	m表示这个二维数组有多少个一维数组
	n表示每一个一维数组的元素个数
举例:
	int[][] arr = new int[3][2];
	定义了一个二维数组arr
	这个二维数组有3个一维数组,名称是arr[0],arr[1],arr[2]
	每个一维数组有2个元素,可以通过arr[m][n]来获取
	表示获取第m+1个一维数组的第n+1个元素
	
格式2
	数据类型[][] 变量名 = new 数据类型[m][];
	m表示这个二维数组有多少个一维数组
	这一次没有直接给出一维数组的元素个数,可以动态的给出。
举例:
	int[][] arr = new int[3][];
	arr[0] = new int[2];
	arr[1] = new int[3]
	arr[2] = new int[1];
	
格式3
	数据类型[][] 变量名 = new 数据类型[][]{{元素…},{元素…},{元素…}};
简化版格式:
	数据类型[][] 变量名 = {{元素…},{元素…},{元素…}};
举例:
	int[][] arr =  {{1,2,3},{4,6},{6}};

练习

(1)P5732 【深基5.习7】杨辉三角

P5732 【深基5.习7】杨辉三角

题目描述

给出 n ( n ≤ 20 ) n(n\le20) n(n20),输出杨辉三角的前 n n n 行。

如果你不知道什么是杨辉三角,可以观察样例找找规律。

样例输入 #1

6

样例输出 #1

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
  • 注意:提交洛谷OJ的时候修改类名为Main
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[][] dp = new int[21][21];
        dp[1][1] = 1;
        for (int i = 2; i <= n; i++)
            for (int j = 1; j <= i; j++)
                dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1];
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(dp[i][j] + " ");
            }
            System.out.println();
        }
    }
}

(2)B2104 矩阵加法

B2104 矩阵加法

题目描述

输入两个 n n n m m m 列的矩阵 A A A B B B,输出它们的和 A + B A+B A+B,矩阵加法的规则是两个矩阵中对应位置的值进行加和,具体参照样例。

输入格式

第一行包含两个整数 n n n m m m,表示矩阵的行数和列数 ( 1 ≤ n ≤ 100 (1 \le n \le 100 (1n100 1 ≤ m ≤ 100 ) 1 \le m \le 100) 1m100)

接下来 n n n 行,每行 m m m 个整数,表示矩阵 A A A 的元素。

接下来 n n n 行,每行 m m m 个整数,表示矩阵 B B B 的元素。

相邻两个整数之间用单个空格隔开,每个元素均在 1 ∼ 1000 1 \sim 1000 11000 之间。

输出格式

n n n 行,每行 m m m 个整数,表示矩阵加法的结果。相邻两个整数之间用单个空格隔开。

样例输入 #1

3 3
1 2 3
1 2 3
1 2 3
1 2 3
4 5 6
7 8 9

样例输出 #1

2 4 6
5 7 9
8 10 12
  • 注意:提交洛谷OJ的时候修改类名为Main
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(), m = sc.nextInt();
        int[][] a = new int[100][100];
        int[][] b = new int[100][100];
        int[][] c = new int[100][100];
        
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++) a[i][j] = sc.nextInt();
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++) b[i][j] = sc.nextInt();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                c[i][j] = a[i][j] + b[i][j];
                System.out.print(c[i][j] + " ");
            }
            System.out.println();
        }
    }
}

(3)B2105 矩阵乘法

B2105 矩阵乘法

题目描述

计算两个矩阵的乘法。 n × m n \times m n×m 阶的矩阵 A A A 乘以 m × k m \times k m×k 阶的矩阵 B B B 得到的矩阵 C C C n × k n \times k n×k 阶的,且 C [ i ] [ j ] = A [ i ] [ 0 ] × B [ 0 ] [ j ] + A [ i ] [ 1 ] × B [ 1 ] [ j ] + C[i][j]=A[i][0] \times B[0][j]+A[i][1] \times B[1][j]+ C[i][j]=A[i][0]×B[0][j]+A[i][1]×B[1][j]+ …… + A [ i ] [ m − 1 ] × B [ m − 1 ] [ j ] ( C [ i ] [ j ] +A[i][m-1] \times B[m-1][j](C[i][j] +A[i][m1]×B[m1][j](C[i][j] 表示 C C C 矩阵中第 i i i 行第 j j j 列元素)。

输入格式

第一行为 n , m , k n,m,k n,m,k,表示 A A A 矩阵是 n n n m m m 列, B B B 矩阵是 m m m k k k 列, n , m , k n,m,k n,m,k 均小于 100 100 100

然后先后输入 A A A B B B 两个矩阵, A A A 矩阵 n n n m m m 列, B B B 矩阵 m m m k k k 列,矩阵中每个元素的绝对值不会大于 1000 1000 1000

输出格式

输出矩阵 C C C,一共 n n n 行,每行 k k k 个整数,整数之间以一个空格分开。

样例输入 #1

3 2 3
1 1
1 1
1 1
1 1 1
1 1 1

样例输出 #1

2 2 2
2 2 2
2 2 2
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(), m = sc.nextInt(), k = sc.nextInt();
        int[][] a = new int[100][100];
        int[][] b = new int[100][100];
        int[][] c = new int[100][100];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)  a[i][j] = sc.nextInt();
        for (int i = 0; i < m; i++)
            for (int j = 0; j < k; j++)  b[i][j] = sc.nextInt();
        for (int i = 0; i < n; i++) 
            for (int p = 0; p < m; p++) 
                for (int j = 0; j < k; j++)   c[i][j] += a[i][p] * b[p][j];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < k; j++) {
                System.out.print(c[i][j] + " ");
            }
            System.out.println();
        }
    }
}

(4)B2106 矩阵转置

B2106 矩阵转置

题目描述

输入一个 n n n m m m 列的矩阵 A A A,输出它的转置 A T A^T AT

输入格式

第一行包含两个整数 n n n m m m,表示矩阵 A A A 的行数和列数。 1 ≤ n ≤ 100 1 \le n \le 100 1n100 1 ≤ m ≤ 100 1 \le m \le 100 1m100

接下来 n n n 行,每行 m m m 个整数,表示矩阵 A A A 的元素。相邻两个整数之间用单个空格隔开,每个元素均在 1 ∼ 1000 1 \sim 1000 11000 之间。

输出格式

m m m 行,每行 n n n 个整数,为矩阵 A A A 的转置。相邻两个整数之间用单个空格隔开。

样例输入 #1

3 3
1 2 3
4 5 6
7 8 9

样例输出 #1

1 4 7
2 5 8
3 6 9
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(), m = sc.nextInt();
        int[][] a = new int[100][100];
        int[][] b = new int[100][100];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                b[j][i] = a[i][j] = sc.nextInt();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(b[i][j] + " ");
            }
            System.out.println();
        }
    }
}

二维数组(Java中无真正的多维数组,只是数组的数组)
C/C++语言的二维数组是矩形;
Java语言的二维数组不一定是矩形。

6. 字符串

用一对双引号""括起来的字符序列。 
Java语言中,字符串常量或变量均用类实现。
字符串变量的创建
格式一:
    String 变量名;
    变量名 = new String("字符串");                          
如:
    String s;    //声明字符串型引用变量s,此时s的值为null
    s=new String("Hello");   //在堆内存中分配空间,并将s指向该字符串首地址 

字符串变量的创建
格式二:String 变量名 = new String("字符串");
如:String s=new String("Hello");

格式三:String 变量名 = "字符串";
   如:String s="Hello";

字符串存储
字符串是引用型变量,所以存储方式与数组基本相同。

串连接
例1:str="Hello"+"Java";   //str的值为"HelloJava“
例2: int i=10;    String s="i="+i;    //s的值为"i=10" 
例3:String str1 = “Java”;   str1 = str1 + “Good”;
   注意:虽然str1指向的内存地址是同一个,但对象已经不是同一个了。
                                   
String 类的常用方法

调用Java语言定义的方法:字符串变量名.方法名();

String 类的常用方法

  1. 字符串查询
    charAt(int index):查找字符串某一位置字符。
    indexOf(String str) :查找某一字符或子字符串在该字符串中的从左边起首次出现的位置,并返回。
    indexOf(String str,int fromIndex) :查找某一字符或子字符串在该字符串中的从fromIndex起首次出现的位置,并返回。
    lastIndexOf(String str) :与indexOf的区别是从末尾开始查找。
    lastIndexOf(String str, int fromIndex) :与lastIndexOf类似,从指定的索引fromIndex开始进行反向搜索。
    contains(CharSequence s) :判断字符串是否包含指定的s值,有则返回 true。

  2. 字符串连接
    concat(String str):字符串连接,将str字符串连接到当前字符串后面,相当于“+”。

  3. 字符串拆分
    split(""):字符串拆分,根据双引号里的内容进行拆分。

  4. 字符串比较
    endsWith(String suffix):判断此字符串是否以指定的后缀结束。
    startsWith(String prefix) :判断此字符串是否以指定的前缀开始。
    compareTo(String anotherString):该方法是对字符串内容按字典顺序进行大小比较,通过返回的整数值指明当前字符串与参数字符串的大小关系。若当前对象比参数大则返回正整数,反之返回负整数,相等返回0。
    compareTolgnore(String anotherString):与compareTo方法相似,但忽略大小写。
    equals(Object anObject) :比较两个字符串的内容,注意不能为null。
    equalsIgnoreCase(String anotherString) :与equals方法相似,但忽略大小写。
    regionMatches(boolean b, int firstStart, String other , int otherStart, int length):从当前字符串的firstStart位置开始比较,取长度为length的一个子字符串,other字符串从otherStart位置开始,指定另外一个长度为length的字符串,两字符串比较,当b为true时字符串不区分大小写。

  5. 字符串转换为数组
    split(String regex) :以regex为分割符,将String字符串转换为String数组。
    toCharArray() :将String字符串转换为char字符数组。
    format(Locale l, String format, Object... args) :格式字符串和参数返回一个格式化字符串。
    getBytes(String charset) :将string转换为byte 数组。
    getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) :将string转换为字符数组

  6. 字符串替换
    matches(String regex) :判断此字符串是否匹配给定的正则表达式。
    replace(char oldChar, char newChar) :将所有 oldChar 替换成newChar,并返回一个新的字符串。
    replaceFirst(String regex, String replacement):该方法用字符replacement的内容替换当前字符串中遇到的第一个和字符串regex相匹配的子串,并返回新的字符串。
    replaceAll(String regex,String replacement):该方法用字符replacement的内容替换当前字符串中遇到的所有和字符串regex相匹配的子串,并返回新的字符串。

  7. StringBuffer类常用方法
    StringBuffer(String str):构造一个字符串缓冲区,并将其内容初始化为指定的字符串内容。
    append(基础类型数据 b):将 基础类型的字符串表示形式追加到序列后面。
    delete(int start, int end):移除此序列的子字符串中的字符。
    deleteCharAt(int index):移除此序列指定位置的 char。
    insert(int offset, 基础类型数据 b):将 基础类型参数的字符串表示形式插入指定位置中。
    toString():返回此序列中数据的字符串表示形式。

  8. 其他
    valueOf(基础数据类型 b) :将基础类型数据的文本转换为字符串
    substring(int beginIndex) :该方法从beginIndex位置截取剩余字符串并返回
    substring(int beginIndex,int endIndex):该方法从beginIndex位置截取到endIndex并返回
    trim():去除字符串两边的空格,中间不做处理。
    isEmpty():当且仅当 length() 为 0 时返回 true。
    toLowerCase() :将String 中的所有字符都转换为小写。
    toUpperCase():将String 中的所有字符都转换为大写。

import java.util.regex.Pattern;

public class Test3 {
    public static void main(String[] args) {
        test01();
        test02();
        test03();
        test04();
        test05();
        test06();
        test07();
    }

    // String 类的常用方法
    // 字符串查询
    // charAt(int index):查找字符串某一位置字符。
    // indexOf(String str):查找某一字符或字符串在该字符串中的从左边起首次出现的位置,并返回。
    // indexOf(String str,int fromIndex):查找某一字符或子字符串在该字符串中的从fromIndex起首次出现的位置,并返回。
    // lastIndexOf(String str):与indexOf的区别是从末尾开始查找。
    // lastIndexOf(String str, int fromIndex):从指定的索引fromIndex开始进行反向搜索。
    // contains(CharSequence s):判断字符串是否包含指定的s值,有则返回 true。
    public static void test01() {
        System.out.println("----------------test01()");
        String s = new String("hello-world!");
        System.out.println(s);

      	System.out.println(s.charAt(0));		// h
        System.out.println(s.charAt(1));		// e
        System.out.println(s.indexOf("world"));	// 6
        System.out.println(s.indexOf("l"));		// 2
        System.out.println(s.indexOf("l", 5));	// 9
        System.out.println(s.lastIndexOf("l"));	// 9
        System.out.println(s.lastIndexOf("l", 5));	// 3
        System.out.println(s.contains("world")); 	// true
        System.out.println(s.contains("World"));	// false
//        s.charAt(index)
    }

    // 字符串连接
    // String concat(String str):字符串连接,将str字符串连接到当前字符串后面,相当于"+"。
    // 字符串拆分
    // split(","):字符串拆分,根据双引号里的内容进行拆分。
    public static void test02() {
        System.out.println("----------------test02()");
        String s = new String("hello");
        System.out.println(s); // hello
       
        System.out.println(s.concat("-world"));// hello-world
        System.out.println(s);// hello

        s = s.concat("-world");
        System.out.println(s);// hello-world

        String[] da = s.split("-");// hello world
        for (int i = 0; i < da.length; i++)
            System.out.println(da[i]);
    }

    // 字符串比较:字典序 ABCDE....
    // endsWith(String suffix):判断此字符串是否以指定的后缀结束。
    // startsWith(String prefix) :判断此字符串是否以指定的前缀开始。
    // compareTo(String otherString):对字符串内容按字典顺序进行大小比较,
    // 通过返回的整数值指明当前字符串与参数字符串的大小关系。
    // 若当前对象比参数大则返回正整数,反之返回负整数,相等返回0。
    // A - B : > < 0
    // compareTolgnore(String anotherString):与compareTo方法相似,但忽略大小写。
    // equals(Object anObject) :比较两个字符串的内容,注意不能为null。
    // equalsIgnoreCase(String anotherString) :与equals方法相似,但忽略大小写。
    // regionMatches(boolean b, int firstStart, String other, int otherStart, int length):
    // 从当前字符串的firstStart位置开始比较,取长度为length的一个子字符串,
    // other字符串从otherStart位置开始,指定另外一个长度为length的字符串,
    // 两字符串比较,当b为true时字符串不区分大小写。
    public static void test03() {
        System.out.println("----------------test03()");
        String s = new String("hello-world!");
        System.out.println(s); // hello-world!
        
        System.out.println(s.endsWith("!"));			// true
        System.out.println(s.startsWith("hi")); 		// false
        System.out.println(s.compareTo("Hello-world!"));// -32
        System.out.println(s.compareToIgnoreCase("Hello-world!"));	// 0
        System.out.println(s.equals("hello-world!"));				// true
        System.out.println(s.equalsIgnoreCase("Hello-world!"));		// true
        System.out.println(s.regionMatches(true, 0, "Hello-world!", 0, 3));// true
        System.out.println(s.regionMatches(false, 0, "Hello-world!", 0, 3));// false
    }

    // 字符串转换为数组
    // split(String regex):以regex为分割符,将String字符串转换为String数组。
    // toCharArray():将String字符串转换为char字符数组。
    // format(Locale l, String format, Object... args) :格式字符串和参数返回一个格式化字符串。
    // byte[] getBytes():使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
    // byte[] getBytes(String charsetName):使用指定的字符集将此 String 编码为 byte 序列
    // void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
    // getChars(...):将字符从此字符串复制到目标字符数组
    public static void test04() {
        System.out.println("----------------test04()");
        String s = new String("AAA BBB CCC DDD EEE FFF");
        System.out.println(s);

        String[] str1 = s.split(" ");
        for (int i = 0; i < str1.length; i++) {
            System.out.println(str1[i]);
        }
        System.out.println();

        char[] str2 = s.toCharArray();
        System.out.println(str2);

        int a = 192, b = 168, c = 0, d = 1;
        
        String formaString = String.format("ip:%d.%d.%d.%d", a, b, c, d);
        System.out.println(formaString);

        byte[] str3 = s.getBytes();
        byte[] str4 = s.getBytes();

        char[] str5 = new char[50];
        s.getChars(0, 5, str5, 0);// AAA BBB CCC DDD EEE FFF
        System.out.println(str5);
    }

    // 字符串替换
    // matches(String regex) :判断此字符串是否匹配给定的正则表达式。
    // 正则表达式:https://www.runoob.com/java/java-regular-expressions.html
    // replace(char oldChar, char newChar) :将所有 oldChar 替换成newChar,并返回一个新的字符串。
    // replaceFirst(String regex, String replacement):
    // 该方法用字符replacement的内容替换当前字符串中遇到的第一个和字符串regex相匹配的子串,并返回新的字符串。
    // replaceAll(String regex,String replacement):
    // 该方法用字符replacement的内容替换当前字符串中遇到的所有和字符串regex相匹配的子串,并返回新的字符串。
    public static void test05() {
        System.out.println("----------------test05()");
        String s = new String("AAA BBB CCC DDD EEE FFF");
        System.out.println(s);

        String content = "www.baidu.com";
        String pattern = ".*com";

        boolean isMatch = Pattern.matches(pattern, content);
        System.out.println("字符串中是否包含了 'com' 子字符串? " + isMatch);
        
        s = s.replace("C", "HH");
        System.out.println(s);
        
        s = s.replace("HH", "hh");
        System.out.println(s);
        
        s = s.replaceAll("hh", "C");
        System.out.println(s);
    }
    
    // StringBuffer类常用方法
    // StringBuffer(String str):构造一个字符串缓冲区,并将其内容初始化为指定的字符串内容。
    // append(基础类型数据 b):将 基础类型的字符串表示形式追加到序列后面。
    // delete(int start, int end):移除此序列的子字符串中的字符。
    // deleteCharAt(int index):移除此序列指定位置的 char。
    // insert(int offset, 基础类型数据 b):将 基础类型参数的字符串表示形式插入指定位置中。
    // toString():返回此序列中数据的字符串表示形式。
    public static void test06() {
    	System.out.println("----------------test06()");
    	StringBuffer s = new StringBuffer("hello");
    	System.out.println(s);
    	
    	s.append("-world");
    	System.out.println(s);
    	
    	s.delete(6, 11);
    	System.out.println(s);
    	
    	s.deleteCharAt(5);
    	System.out.println(s);
    	
    	s.insert(5, "-world");
    	System.out.println(s);
    	System.out.println(s.toString());
    }
    
    // 其他
    // valueOf(基础数据类型 b) :将基础类型数据的文本转换为字符串
    // substring(int beginIndex) :该方法从beginIndex位置截取剩余字符串并返回
    // substring(int beginIndex,int endIndex):该方法从beginIndex位置截取到endIndex并返回
    // trim():去除字符串两边的空格,中间不做处理。
    // isEmpty():当且仅当 length() 为 0 时返回 true。
    // toLowerCase():将String 中的所有字符都转换为小写。
    // toUpperCase():将String 中的所有字符都转换为大写。
    public static void test07() {
    	System.out.println("----------------test08()");
    	String s = new String("hello-world");
    	System.out.println(s);
    	
    	String s1 = s.substring(6);
    	System.out.println(s1);
    	
    	String s2 = s.substring(0, 5); // [l, r)
    	System.out.println(s2);
    	
    	s = s.trim();
    	System.out.println(s);
    	boolean f = s.isEmpty();
    	
    	s=s.toLowerCase();
    	System.out.println(s);
    	
    	s=s.toUpperCase();
    	System.out.println(s);
    }
}

参考资料

https://www.runoob.com/java/java-stringbuffer.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值