java - 调用方法、参数和参数
问题描述
这可能是一个愚蠢的问题。我的以下代码看起来不错,但在输出上,它并不期望我的测试场景有结果。代码如下:
import java.util.Scanner;
public class PartyPlannerLab {
public static Scanner input = new Scanner(System.in);
public static int getGuestCount(int guests) {
while(true) {
System.out.print("Enter number of guests: ");
guests = input.nextInt();
if (guests >= 1 && guests <= 100)
break;
else
System.out.println("The guest count must be at least 1, but does not exceed 100. Please enter again.");
}
return guests;
}
public static int getSlicesPerPerson(int slicesPerPerson) {
while(true) {
System.out.print("Enter number of slices per person: ");
slicesPerPerson = input.nextInt();
if (slicesPerPerson >= 1 && slicesPerPerson <= 8)
break;
else
System.out.println("The pizza slice count must be at least 1, but does not exceed 8. Please try again.");
}
return slicesPerPerson;
}
public static double computeRoomCost(int guests, double roomCost) {
if (guests <= 30)
roomCost = 100.00;
else
roomCost = 200.00;
return roomCost;
}
public static double computeSodaCost(double sodaCost, int guests) {
sodaCost = guests * 1.50;
return sodaCost;
}
public static void printSummary(int guests, double roomCost, double sodaCost, double pizzaCost) {
System.out.println("Total Guests: " + guests);
System.out.println("RoomCost: $" + roomCost);
System.out.println("SodaCost: $" + sodaCost);
System.out.println("PizzaCost: $" + pizzaCost);
System.out.println("Total Cost: $" +(roomCost + sodaCost + pizzaCost));
}
public static void main(String[] args) {
int guests = 0;
int slicesPerPerson = 0;
double roomCost = 0.0;
double sodaCost = 0.0;
double pizzaCost = 0.0;
getGuestCount(guests);
getSlicesPerPerson(slicesPerPerson);
computeRoomCost(guests, roomCost);
computeSodaCost(sodaCost, guests);
printSummary(guests, roomCost, sodaCost, pizzaCost);
input.close();
}
}
一个输出如下:
Enter number of guests: 10
Enter number of slices per person: 2
Total Guests: 0
RoomCost: $0.0
SodaCost: $0.0
PizzaCost: $0.0
Total Cost: $0.0
解决方案
您没有得到输出的原因是您在 main 方法中初始化的值没有随着您正在进行的方法调用而更新。
下面的代码可能会解决您面临的问题 -
public static void main(String[] args) {
int guests = 0;
int slicesPerPerson = 0;
double roomCost = 0.0;
double sodaCost = 0.0;
double pizzaCost = 0.0;
guests = getGuestCount(guests);
slicesPerPerson = getSlicesPerPerson(slicesPerPerson);
roomCost = computeRoomCost(guests, roomCost);
sodaCost = computeSodaCost(sodaCost, guests);
printSummary(guests, roomCost, sodaCost, pizzaCost);
input.close();
}
注意 -不需要在getGuestCount 和 getSlicesPerPerson方法中传递参数,因为输入是从 I/O 获取的
推荐阅读
- python - 如何使用 OpenCV Python 一次性从大量视频中提取和保存图像帧?
- android - Android - 更新计费库产品的 onSkuDetailsResponse 按钮
- node.js - 如何在 Angular 12 中使用加密(方法:randomBytes()、createCipheriv()、createDecipheriv())或类似方法?
- qt - QT ModelView:在 QAbstractItemModel 中使用共享指针的示例
- python - 为什么不能将 NaN 的 pandas 数据框值用作字典键?
- javascript - Youtube 音频立体声声像
- dart - 正好两种类型的 Dart 列表
- android - 如何使用 SHA256 算法签署 .apk
- docusignapi - DSA Web 应用程序和客户端应用程序上的 DocuSign 基本 URL 和资源路径位置
- keycloak - Keycloak 向客户端添加资源