import导包,Scanner sc=new Scanner(System.in),new一个新对象,int money=sc.nextInt(),
这三部相当于c/c++的输入
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("请输入你要购买机票的月份");
int month=sc.nextInt();
System.out.println("请输入你要购买机票的座舱");
int seet=sc.nextInt();
System.out.println("请输入你要购买机票的原价");
int money =sc.nextInt();
if(month>=5&&month<=10){
//旺季
if(seet ==1){
money=(int)(0.9*money);
}else if(seet ==0){
money=(int)(0.85*money);
}
}else if((month>=1&&month<=4)|(month<=12&&month>=11)){
//淡季
if(seet ==1){
money=(int)(0.63*money);
}else if(seet ==0){
money=(int)(0.73*money);
}
}else{
System.out.println("你要购买的月份不合法");
}
System.out.println(money);
}
}
这几步可以用java的提取方法快捷键ctrl+alt+m
if(seet ==1){
money=(int)(0.9*money);
}else if(seet ==0){
money=(int)(0.85*money);
}
直接提取出来方法,也就是c/c++的函数
private static int getMoney(int seet, int money) {
if(seet ==1){
money =(int)(0.9* money);
}else if(seet ==0){
money =(int)(0.85* money);
}
return money;
}
把private改为public就可以了,一个方法就此诞生
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("请输入你要购买机票的月份");
int month=sc.nextInt();
System.out.println("请输入你要购买机票的座舱");
int seet=sc.nextInt();
System.out.println("请输入你要购买机票的原价");
int money =sc.nextInt();
if(month>=5&&month<=10){
//旺季
money = getMoney(seet, money, 0.9, 0.85);
}else if((month>=1&&month<=4)|(month<=12&&month>=11)){
//淡季
money = getMoney(seet, money, 0.63, 0.73);
}else{
System.out.println("你要购买的月份不合法");
}
System.out.println(money);
}
private static int getMoney(int seet, int money, double x, double x1) {
if (seet == 1) {
money = (int) (x * money);
} else if (seet == 0) {
money = (int) (x1 * money);
}
return money;
}
}