Java 从另一种方法编辑案例陈述?
对于我正在为学校编写的一个程序,其中一个扩展说,如果我以管理员身份输入,我需要找到一种编辑案例语句的方法,我创建了两种方法,因为这似乎是最好的方法 方法一(我需要编辑的方法):Java 从另一种方法编辑案例陈述?,java,methods,case-statement,Java,Methods,Case Statement,对于我正在为学校编写的一个程序,其中一个扩展说,如果我以管理员身份输入,我需要找到一种编辑案例语句的方法,我创建了两种方法,因为这似乎是最好的方法 方法一(我需要编辑的方法): 如果用另一种方法做不到,但它是用同一种方法做的,请解释一下,我可以把它做成一个大方法。谢谢。您可以使用管理模式的标志。将其设置为true,您将处于管理模式: boolean admin=true 然后,您可以简单地检查admin是否为true,如果是这样,则打印admin内容,如果不是。。。打印这些正常输出 用户键入1时
如果用另一种方法做不到,但它是用同一种方法做的,请解释一下,我可以把它做成一个大方法。谢谢。您可以使用管理模式的标志。将其设置为true,您将处于管理模式:
boolean admin=true
然后,您可以简单地检查admin
是否为true
,如果是这样,则打印admin内容,如果不是。。。打印这些正常输出
用户键入1时的示例:
case 1:
if(admin)
{ //admin, change price
c.println("Please enter the new price for the Low Pile Carpet: ");
pileCost = c.readInt();
}
else
{ //non-admin, set price
price = 18.75;
}
break; //important! don't forget the break-keyword
如果忘记在case语句末尾添加break
,则将运行以下所有语句(例如,对于2:3,4,5..)
这应该是一个灵感,你应该自己解决剩下的问题:)
哦,当然,这样你只会得到一种方法,这比之前两种方法的组合要小,因为逻辑是不重复的。请用你正在使用的语言标记你的问题。这是Java吗?是的,对不起,我在这里发布的第一个问题是:请更改所提问题的标记,否则会有人投票否决它。我不确定你说的是什么标记,它是Java中关于方法和case语句的?谢谢!这种方式比我当时的方式更有意义。不过,我遇到的唯一真正的大问题是删除或添加管理员想要添加的case语句?您如何通过控制台本身“添加”某些内容?如果有像0这样的键只针对管理员,只需检查admin=true,如果不是,则什么也不做。这是我的分配文件“4”中所说的。你能想出一种方法,将地板类型和成本转换为允许程序的“管理员”更改价格、添加和删除项目等的格式吗因此,我也必须能够添加新的地板类型或删除它们。有什么想法吗?你可以把它们放在
地图中
,键是物品的名称,值是你的价格。那么你就不再需要这个案例了,因为你可以迭代映射
,更改它的值,添加和删除它们等等。但这是一种不同于你现在的方法。如果我要求新的地板类型名称和另一个数组的价格,数组会起作用吗?
public static void admin(Console c) {
int choice = 0, priceChange = 0;
cls(c);
c.println("Hello admin. What changes would you like to make?");
c.println("1. Change a price.");
c.println("2. Add an item.");
c.println("3. Remove an item.");
switch(choice){
//Changing the price of an item
case 1:
c.print("What price would you like to change? ");
c.println("1. Low Pile Carpet.");
c.println("2. Shag Rug.");
c.println("3. Parquet.");
c.println("4. Linleum.");
c.println("5. Hardwood.");
switch(priceChange){
case 1:
c.println("Please enter the new price for the Low Pile Carpet: ");
pileCost = c.readInt();
case 2:
c.println("Please enter the new price for the Shag Rug: ");
rugCost = c.readInt();
case 3:
c.println("Please enter the new price for the Parquet: ");
parquetCost = c.readInt();
case 4:
c.println("Please enter the new price for the Linluem: ");
leumCost = c.readInt();
case 5:
c.println("Please enter the new price for the Hardwood: ");
hardwoodCost = c.readInt();
}
//Adding an item
case 2:
//Removing an item
case 3:
}
case 1:
if(admin)
{ //admin, change price
c.println("Please enter the new price for the Low Pile Carpet: ");
pileCost = c.readInt();
}
else
{ //non-admin, set price
price = 18.75;
}
break; //important! don't forget the break-keyword