我有一个家庭作业,我应该写几个方法(例如,提示客户输入汽车类型并返回有效汽车类型的方法),然后我的程序应该显示汽车类型,租车天数,额外费用等。这是老师想让我写的第一种方法,
public static String promptForCarType(){
Scanner input = new Scanner(System.in);
char type;
System.out.println("(E) Economy - 50 TL");
System.out.println("(M) Midsize - 70 TL");
System.out.println("(F) Fullsize - 100 TL");
do{
System.out.println("Enter the car type (E/M/F) : ");
type = input.next().charAt(0);
type = Character.toUpperCase(type);
} while (type != 'E' && type != 'M' && type != 'F' ); //I tried to define condition with "||" operator,didn't work.
switch(type) {
case 'E' : ;return "Economy";
case 'M' : return "Midsize";
case 'F' : return "Fullsize";
default : return " ";
}
}
如何打印出此方法的返回值?我应该添加系统吗?(“汽车类型是...部分在提示为汽车类型()?
代码控件在遇到关键字return时返回调用函数。因此,在程序达到关键字return之前,只能使用当前方法进行操作。所以,如果你需要打印一些东西,请在退货前打印出来。在您的例子中,您需要为return语句之前的每个case打印switch case构造中的值。
switch(type) {
case 'E' : System.out.println("Economy");
return "Economy";
// similarly for each switch case.
}
或者,更好的方法是将汽车类型分配给String类型的变量,然后打印值。并为整个方法编写一个公共返回语句(适用于所有情况)。
String carType;
switch(type) {
case 'E' : carType ="Economy";
// similarly for each switch case.
}
System.out.println(carType);
return carType;
>
打印该变量
String carType = promptForCarType(); //1 + 2
System.out.println(carType); //3
或者简单地说
System.out.println(promptForCarType());
如果要打印汽车类型的实例,只需转到main方法并打印访问方法promptForCar的汽车的调用实例。例如:System.out.println(object.method);