JAVA经典小例子(三)
万年历
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
随机生成时期双色球中奖号码
import java.util.Random;
public class xxx {
public static void main(String[] args) {
Random random = new Random();
int[][] arr = new int[10][7];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = random.nextInt(33) + 1;
if (j == 6) {
arr[i][j] = random.nextInt(16) + 1;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.print("第" + (i + 1) + "期中奖号码\t");
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + "\t\t");
}
System.out.print("\n");
}
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
用函数调用将计算器功能实现
import java.util.Scanner;
public class Calculator{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("请输入第一个数:");
int num1 = scan.nextInt();
System.out.println("请输入第二个数:");
int num2 = scan.nextInt();
System.out.println("请输入运算符:1+,2*,3/,4-");
int operator = scan.nextInt();
switch (operator) {
case 1:
int result = add(num1, num2);
System.out.print("result:" + result);
break;
case 2:
int result1 = mul(num1, num2);
System.out.print("result:" + result1);
break;
case 3:
double result2 = div(num1, num2);
System.out.print("result:" + result2);
break;
case 4:
int result3 = sub(num1, num2);
System.out.print("result:" + result3);
break;
}
return ;
}
/**
*
* @param num1 第一个操作数
* @param num2 第二个操作数
* @return 当传入两个操作数时返回两个操作数的和,返回值用于主方法中输出结果
*/
public static int add(int num1, int num2) {
return num1 + num2;
}
public static int mul(int num1, int num2) {
return num1 * num2;
}
public static double div(double num1, double num2) {
return num1 / num2;
}
public static int sub(int num1, int num2) {
return num1 - num2;
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
调用函数时传入基本数据类型,不会改变传入的变量值.
但是传入数组时(引用数据类型),会改变传入的数组的值
函数重载:
* 有参和无参
* 同为有参但是参数的数量不一致
* 同为有参但是参数的类型不一致
* 同为有参当类型和数量一致,但是顺序不一致时也是重载.
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println("a:"+a+",b:"+b);
change(a,b);
System.out.println("a:"+a+",b:"+b);
int[] arr = {1,2,3,4,5};
change(arr);
System.out.println(arr[1]);
}
//以下change方法重载
public static void change(int a,int b) {
System.out.println("a:"+a+",b:"+b);
a = b;
b = a + b;
System.out.println("a:"+a+",b:"+b);
}
public static void change(int[] arr) {
for(int x=0; x<arr.length; x++) {
if(arr[x]%2==0) {
arr[x]*=2;
}
}
}