(一)使用方法实现求和
public class menthod { public static void main(String[] args) { //小莉 int s=sum(10,20); System.out.println(s); //小王 int t=sum(s,8); System.out.println(t); } public static int sum(int a,int b){//int 是返回类型,sum是方法名称 int c=a+b; return c; } }
//无参数无返回值
public static void print(){
System.out.println(“无参数无返回值”);
}
//传递数组
public class menthod { public static void main(String[] args) { int[] w={1,2,3,6,3}; printfnum(w); } public static void printfnum(int[] w){ for(int i=0;i<w.length;i++){ System.out.println(w[i]); } } }
(一)买飞机票
public class BuyFlyTicket {
public static void main(String[] args) {
double price=123.98;
int month=2;
int c=1;//1为头等舱,0为经济舱
double need=0;
switch(month) {
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
if (c == 0) {
need =price*0.85;
} else if (c == 1) {
need =price*0.9;
}
break;
case 11:
case 12:
case 1:
case 2:
case 3:
case 4:
if (c == 0) {
need =price*0.65;
} else if (c == 1) {
need =price*0.7;
}
break;
default:
System.out.println("error");
}
System.out.println("价格为"+need);
// System.out.println("月份%的价格为".codePointAt(month));
}
}
(二)随机生成验证码
import java.util.Random;
public class Code {
public static void main(String[] args) {
//生成随机验证码
String code=creatCode(10);
System.out.println(code);
}
public static String creatCode(int n){//验证码位数
String s="";
//由于验证码有数字,大写字母和小写字母,随机一个0~2数字,分别表示应该生成什么类型
for(int i=1;i<=n;i++){
Random R=new Random();
int type=R.nextInt(3);
if(type==0){//0~9数字
int r=R.nextInt(10);
s=s+r;
}
else if(type==1){
char r=(char)(R.nextInt(26)+'a');
s+=r;
}
else if(type==2){
char r=(char)(R.nextInt(26)+'A');
s+=r;
}
}
return s;
}
}
(三)找素数
判断101-200之间有多少个素数,并输出所有素数。
//素数是除了1和它本身以外,不能被其他正整数整除的数
eg:3,7是素数,而9,21不是素数
public class primeNumber {
public static void main(String[] args) {
int total=0;
for(int i=101;i<=200;i++){
boolean t=check(i);
if(!t){
total++;
System.out.println(i);
}
}
System.out.println("一共"+total+"个");
}
public static Boolean check(int num){
Boolean t=false;
for(int i=2;i<num;i++){
if(num%i==0){//能整除
t=true;
}
}
return t;
}
}