我已經淘到谷歌和SO沒有運氣到目前爲止。這可能是由於我缺乏知識,也很難知道如何正確搜索我的答案。Java:聲明一個字符串參數的方法
概念,我想有一個期待字符串的方法,然後使用該字符串的代碼塊中,以引導基本System.out.println
import java.util.HashMap;
public class Restaurant {
public static void main(String[] args) {
HashMap<String, Integer> restaurantMenu = new HashMap<String, Integer>();
restaurantMenu.put("Turkey Burger",13);
restaurantMenu.put("Naan Pizza",11);
restaurantMenu.put("Cranberry Kale Salad",10);
seePrice("Naan Pizza");
/* I want to create a method called seePrice, which expects a string input
(which will ultimately be a name of one of the food items on the menu).
Then it goes on to use that string input in:
System.out.println(restaurantMenu.get(stringinputgoeshere));
So that I can simply type seePrice("Naan Pizza");
and it will display the price in the console
*/
}
}
很多不同的嘗試後,我不能讓這樣的東西基本爲我工作。請原諒我是這樣的新手。所有的幫助表示讚賞。
編輯以下(注意一些多餘的物品,如平方英尺行被加到簡單地進一步良好做法getter和setter方法)
import java.util.HashMap;
public class Restaurant {
//sqft section
private double sqft = 0.0;
public Restaurant(){
sqft = 500.0;
}
public Restaurant(double squareFeet){
sqft = squareFeet;
}
public double getSqft(){
return sqft;
}
//Menu section
private HashMap<String, Double> restaurantMenu = new HashMap<String, Double>();
public int setMenu(HashMap<String, Double> currentMenu){
this.restaurantMenu = currentMenu;
return 1;
}
public HashMap<String, Double> getMenu(){
return restaurantMenu;
}
public static void seePrice (HashMap<String, Double> menu, String food){
System.out.println(menu.get(food));
}
/////////Run Main Section Here
public static void main(String[] args) {
Restaurant platefulOfCox = new Restaurant(2120.8);
System.out.println("The square footage is "+platefulOfCox.getSqft());
HashMap<String, Double> tempMenu = new HashMap <String, Double>();
tempMenu.put("Pizza",10.99);
tempMenu.put("Burger",5.95);
tempMenu.put("Coke",1.99);
platefulOfCox.setMenu(tempMenu);
//Price Checker
String foodItem = "Coke";
seePrice(platefulOfCox.getMenu(),foodItem);
}
}
請正確描述你的問題,如果你只是想接受一個字符串的方法然後(public void myMethod(string st){System.out.println(st)})將是你的答案 –