【发布时间】:2019-09-27 09:48:41
【问题描述】:
我正在尝试这样做:如果用户选择此选项,程序会将读入的数据打印到屏幕上。
样本输出:
日期:2018 年 1 月 10 日输出:236.9 日期:2018 年 1 月 11 日产量:267.6 日期:2018 年 1 月 12 日输出:278.1
编写一个名为 PrintData 的方法来完成此任务。选择适当的参数和返回类型。
打印完成后,将再次显示主菜单。
我已经在我的上传数据方法中将数据读入我的数组列表,我现在正试图弄清楚如何制作一个单独的方法来打印 UploadData 的数组列表。
我不认为我现在拥有的东西不会起作用。
: ` public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
//calling menu
showMenu();
int userChoice=keyboard.nextInt();
while (userChoice == 1)
{
UploadData();
showMenu();
int userchoice=keyboard.nextInt();
}
while(userChoice ==2)
{
PrintData();
showMenu();
int userchoice=keyboard.nextInt();
}
}
public static void showMenu()
{
//creating menu
System.out.println("Welcome to the Power Plant Analyzer program. Please choose from the following options:\n"
+ " 1. Upload Data\n 2. View Data \n 3. Download Statistics \n 4. Print Month \n 5. Exit the program");
}
public static String[] UploadData() throws IOException
{
Scanner keyboard = new Scanner(System.in);
//Asking for file
System.out.println("What is the name of the file that contains the data?");
String inputFileName=keyboard.nextLine();
//creating file
File f = new File(inputFileName);
Scanner inputFile = new Scanner(f);
//creating arraylist
ArrayList<Entry> MonthList = new ArrayList<>();
//reading the file
while(inputFile.hasNext())
{
//read a line
String m = inputFile.next();
String d = inputFile.next();
String y = inputFile.next();
float p = inputFile.nextFloat();
//create Entry with info read in
Entry i = new Entry(m,d,y,p);
//add it to the arraylist
MonthList.add(i);
}
//print Entry's into arraylist
//for(int i =0; i <MonthList.size(); i++)
//MonthList.get(i).print();
return null;
}
public static void PrintData(ArrayList<Entry> MonthList)
{
for(int i =0; i <MonthList.size(); i++)
MonthList.get(i).print();
//ArrayList<Entry> MonthList = new ArrayList<>(Arrays.asList());
//int pos = Collections.binarySearch(MonthList);
}
}`
//declaring variables
private String month;
private String day;
private String year;
private float powerOutput;
//Constructors
public Entry(){}
public Entry (String m, String d, String y, float p)
{
month = m;
day =d;
year =y;
powerOutput=p;
}
//creating print to call ArrayList in main
public void print()
{
System.out.println("Month: " + month + " Day: " + day + " Year: " + year + " Power Output: " + powerOutput);
}
}
【问题讨论】:
-
不相关:尝试使用有意义的名称,即使是参数名称也应该超过 m d y p。并且:始终遵循 java 约定。方法是 camelCase(),所以不要做一些 camelCase() 和一些 UpperCase()。
-
对于我主要的这一行:PrintData();我收到一个错误“类 Project 中的方法 PrintData 不能应用于给定类型:必需:ArrayList
-
MonthList是静态声明项吗? -
我不太确定,但我想是的
标签: java arrays class arraylist methods