习题1:字符串排序
用Java编写一个能对一组字符串按字典序升序排序的程序 输入为N和N行字符串,需要按行输出字符串升序排序的结果 如输入
3
Abc
Abe
Abd
输出:
Abc
Abd
Abe
代码:
import java.io.BufferedReader;import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Collections; import java.util.Scanner;public class Main { public static void main(String args[]){ Scanner scanner = new Scanner(System.in); int sc = scanner.nextInt(); String[] array = new String[sc]; for (int i=0;i<array.length;i++) { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str = null; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } array[i] = scanner.next(); } Arrays.sort(array); for (String arrays:array) { System.out.println(arrays); }}}
习题2:求斐波拉契数
斐波拉契数为,Fib(N) = Fib(N-1)+Fib(N-2) F(0)=F(1)=1 用Java编写能求Fib(N)的程序 输入为N,须输出Fib(N)
如输入
3
输出:
3
代码:
import java.util.Scanner;public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int a = sc.nextInt(); System.out.println(Fib2(a)); } public static long Fib2(int n){ if(n==0||n==1) return 1; long x0=1; long x1=1; long x2 = x0+x1; for(int i =2;i<=n;i++){ x2 = x0+x1; x0=x1; x1=x2; } return x2; } }
习题3:交集
给定两个数组(数组中不包含相同元素),求两个数组的交集中元素的个数(即共同出现的数,如没有则输出为None) 如输入:
5
1 2 4 6 8
6
1 2 5 6 7 8
输出: 4
代码:
import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub int n1,n2,times=0; System.out.println("数组1的的长度:"); Scanner in=new Scanner(System.in); n1=in.nextInt(); long[] array1=new long[n1]; for(int N1=0;N1<n1;N1++) { System.out.println("数组1的元素:"); array1[N1]=in.nextLong(); } System.out.println("数组2的的长度:"); n2=in.nextInt(); long[] array2=new long[n2]; for(int N2=0;N2<n2;N2++) { System.out.println("数组2的元素:"); array2[N2]=in.nextLong(); } in.close(); for(int count01=0;count01<n1;count01++) { for(int count02=0;count02<n2;count02++) { if(array1[count01]==array2[count02]) times+=1; } } System.out.println(times); } }