java基础
/*
* java里不能使用人们熟悉的算术运算符处理大数值 而需要使用大数值类中的add和multiply方法
* BigInteger c = a.add(b)// c = a+b;
* BigInteger d = c.multiply(b.add(BigInteger.valueOf(2)))// d = c *(b+2)
* */
如计算n*(n-1)*...*(n-k+1) / (1*2*...k);
package welcome; import java.math.BigInteger; import java.util.Scanner; public class welcome { public static void main(String[] args) { Scanner in = new Scanner(System.in); int k = in.nextInt(); int n = in.nextInt(); BigInteger lotteryOdds = BigInteger.valueOf(1); for(int i=1;i<=k;i++) { lotteryOdds = lotteryOdds.multiply(BigInteger.valueOf(n-1-i)).divide(BigInteger.valueOf(i)); } System.out.println("Your odds are 1 in "+ lotteryOdds +".Good luck"); } }
将一个数组的元素拷贝到另外一个数组中 调用这个方法的语法格式 System.arraycopy(from,fromIndex,to,toIndex,count)
实例:
package welcome1; import java.util.Scanner; public class welcome1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int[] smallPrimes = {2,3,5,7,11,13}; int[] luckyNumbers = {1001,1002,1003,1004,1005,1006,1007}; System.arraycopy(smallPrimes,2,luckyNumbers,3,4); for(int i=0;i<luckyNumbers.length;i++) { System.out.println(i+":"+luckyNumbers[i]); } } }
输出:
0:1001
1:1002
2:1003
3:5
4:7
5:11
6:13
数组排序调用Arrays类中的sort // Array.sort(a);
实例:
package LotteryDrawing; import java.util.Arrays; import java.util.Scanner ; public class LotteryDrawing { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("How many numbers do you need to draw"); int k = in.nextInt(); System.out.print("what is the highest number you can draw"); int n = in.nextInt(); int[] numbers = new int[n]; for(int i=0;i<numbers.length;i++) { numbers[i] = i +1; } int[] result = new int[k]; for(int i=0;i<result.length;i++) { int r = (int)(Math.random()*n); result[i] = numbers[r]; numbers[r] = numbers[n-1]; n--; } Arrays.sort(result); System.out.println("Bet the following combination.It'll make you rich!"); for(int r:result) System.out.println(r); } }