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

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

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

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

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

  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; 
  1. 从main方法调用您的方法
  2. 将反复值分配给变量
  3. 打印那个变量

     String carType = promptForCarType(); //1 + 2 System.out.println(carType); //3 

或者干脆

 System.out.println(promptForCarType()); 

如果你想打印汽车类型的实例,你只需要转到main方法并打印汽车的被调用实例,访问方法promptForCar。 例如:System.out.println(object.method);

 String carType = promptForCarType(); System.out.println("Car type is: " + carType); 

应该管用。 promptForCar()的返回值存储在字符串carType中,然后print语句使用字符串变量来打印返回值。 `

您可以从无限循环返回(并简化您的代码),就像这样 –

 public static String promptForCarType() { Scanner input = new Scanner(System.in); char type; for (;;) { System.out.println("(E) Economy - 50 TL"); System.out.println("(M) Midsize - 70 TL"); System.out.println("(F) Fullsize - 100 TL"); System.out.println("Enter the car type (E/M/F) : "); type = input.next().charAt(0); type = Character.toUpperCase(type); switch (type) { case 'E': return "Economy"; case 'M': return "Midsize"; case 'F': return "Fullsize"; } } }