提问人:sakif 提问时间:1/18/2023 最后编辑:sakif 更新时间:1/18/2023 访问量:71
我们可以在构造函数类中调用其他方法中的方法吗?
Can we call a method in other method in constructor class?
问:
例如,我创建了一个类 Pizza,它有 pizzaCodes() 和 pizzaSizes() 方法。我在 pizzaCodes() 方法中使用了 pizzaSizes() 方法(接受输入并返回值)。pizzaCodes() 的代码如下:
public String pizzaCodes(){
Scanner sc = new Scanner(System.in);
System.out.println("Choose your pizza: ");
code = sc.next().charAt(0);
switch(code){
case 'A', 'a':
System.out.println("Pizza: " + pizzaCode[0]);
System.out.println("Choose size(R/L): ");
pizzaSizes(size); // pizzaSizes() method used in pizzaCodes() method.
if(pizzaSize == 'R'){
dPizza = "Chicken Delight: Regular";
price2 = price[0];
}else{
dPizza = "Chicken Delight: Large";
price2 = price[3];
}
System.out.println("Quantity?");
quantity = sc.nextInt();
break;
case 'B', 'b':
System.out.println("Pizza: " + pizzaCode[1]);
System.out.println("Choose size(R/L): ");
pizzaSizes(size); // pizzaSizes() method used in pizzaCodes() method.
if(pizzaSize == 'R'){
dPizza = "Beef Pepperoni: Regular";
price2 = price[1];
}else{
dPizza = "Beef Pepperoni: Large";
price2 = price[4];
}
System.out.println("Quantity?");
quantity = sc.nextInt();
break;
case 'C', 'c':
System.out.println("Pizza: " + pizzaCode[2]);
System.out.println("Choose size(R/L): ");
pizzaSizes(size); // pizzaSizes() method used in pizzaCodes() method.
if(pizzaSize == 'R'){
dPizza = "Cheese Bomb: Regular";
price2 = price[2];
}else{
dPizza = "Cheese Bomb: Large";
price2 = price[5];
}
System.out.println("Quantity?");
quantity = sc.nextInt();
break;
case 'D', 'd':
dPizza = "Super Deals";
System.out.println("Pizza: " + pizzaCode[3]);
System.out.println("Choose size(R/L): ");
pizzaSizes(size); // pizzaSizes() method used in pizzaCodes() method.
System.out.println("Quantity?");
quantity = sc.nextInt();
break;
}
total = price2 * quantity;
totPrice = total + totPrice;
if(totPrice > 50){ // if else for applying discount
newPrice = totPrice - 20;
System.out.println("Discount applied");
System.out.println("Total amount :RM" + String.format("%.2f", newPrice));
}else{
newPrice = totPrice;
System.out.println("No discount applied");
System.out.println("Total amount :RM" + String.format("%.2f", newPrice));
}
return dPizza;
}
这是 pizzaSizes() 代码:
public String[] pizzaSizes(String[] size){
Scanner sc = new Scanner(System.in);
pizzaSize = sc.next().charAt(0);
if(pizzaSize == 'R'||pizzaSize == 'r'){
System.out.println("Size: " + size[0]);
}else{
System.out.println("Size: " + size[1]);
}
return size;
}
我期待一个错误,因为我学会了在 main 方法中调用一个方法,而且我是 java 编码的新手,但它工作得很好。我真的很好奇它是否真的违反了 java 规则。
答: 暂无答案
评论
constructor class