如何只打印出方法的返回值?

v_7*_*v_7 1 java

我有一个家庭作业,我应该写几个方法(例如,提示客户的汽车类型并返回有效的汽车类型的方法)然后我的程序应显示汽车类型,汽车租用的天数,额外这是老师要我写的第一种方法,

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 " ";

        }


    }
Run Code Online (Sandbox Code Playgroud)

如何只打印出此方法的返回值?我应该在promptForCarType()中添加System.out.println("Car type is ...")部分吗?

Ada*_*rsh 5

代码控件在遇到关键字return时返回到调用函数.因此,您只能在当前方法中操作,直到程序到达关键字返回.因此,如果您需要打印某些东西,请在返回之前打印.在您的情况下,您需要在switch语句构造中打印值,对于return语句之前的每种情况.

 switch(type) {
        case 'E' : System.out.println("Economy");
                   return "Economy";             
       // similarly for each switch case.
    }
Run Code Online (Sandbox Code Playgroud)

或者,更好的方法是将汽车类型分配给String类型的变量,然后打印该值.并为整个方法(对于所有情况)编写一个公共返回语句.

   String carType;
   switch(type) {
        case 'E' : carType ="Economy";
       // similarly for each switch case.
    }
    System.out.println(carType);
    return carType;
Run Code Online (Sandbox Code Playgroud)

  • 只有在调用它时才会输入方法.因此,您可以在方法内部或在调用promptForCarType()的方法内打印,如A4L所示.无论哪种方式,它的正确和做同样的事情. (2认同)