关于Java,自己编写一个constructor来实现文件里面数据的随机抽取
关于Java,自己编写一个constructor来实现文件里面数据的随机抽取Your Community Supported Agriculture(CSA) farm delivers a box of fresh fruits and vegetables to your house once a week. For this Programming, define the class BoxOfProduce that contains exactly three bundles of fruits or vegetables. You can represent the fruits or vegetables in three fields of type String. You can create a no-arg constructor that randomly selected three items for the three fields from this list:
Broccoli
Tomato
Kiwi
ale
Tomatillo
This list is stored in the text file, itemList.txt that is read by your program.Add accessor and mutator methods to get or set the fruits or vegetables stored in these
fields. Also write an output method that displays the complete contents of the box.
Write a main method that creates a BoxOfProduce object. Next, the main method should display the contents of the box and allow the user to substitute any one of the
five possible fruits or vegetables for any of the fruits or vegetables selected for the box. After the user is done with substitutions, output the final contents of
the box to be delivered. The program should produce output similar to that shown below.
The contents of the box:
Item1: Tomatillo
Item2: Broccoli
Item3: Broccoli
Do you agree with the selected item1,
Tomatillo(Yes or No): Yes
Do you agree with the selected item2,
Broccoli(Yes or No): No
Enter the substituting fruit or vegetable
for item2: Tomato
Do you agree with the selected item3,
Broccoli(Yes or No): No
Enter the substituting fruit or vegetable
for item3: Kiwi
The contents of the box:
Item1: Tomatillo
Item2: Tomato
Item3: Kiwi
接下来是我自尝试写的类,但是不知道应该在main函数里要怎么用,没有什么思路,感觉一整道题目下来思路都不清楚。
public class BoxOfProduce {
private String Item1;
private String Item2;
private String Item3;
private String names;
public String line(int num) throws IOException {
int i;
String Item = null;
File file = new File("itemList.txt");
Scanner inputFile = new Scanner(file);
for (i = 0; i <= num; i++) {
Item.equals(inputFile.next());
}
inputFile.close();
return Item;
}
public BoxOfProduce() throws IOException{
int num;
Random rd = new Random();
num = rd.nextInt(5);
System.out.println("Item1:"+Item1.equals(line(num)));
num = rd.nextInt(5);
System.out.println("Item2:"+Item2.equals(line(num)));
num = rd.nextInt(5);
System.out.println("Item3:"+Item3.equals(line(num)));
}
public void mutator(String fruitsname) {
names = fruitsname;
}
public String accessor() {
return names;
}
public static void main(String[] arrgs) throws IOException{
BoxOfProduce BoxOfProduce=new BoxOfProduce();
System.out.println("Do you agree with the selected "+"(Yes or No):");//这句话是我随便写的
}
}
[ 本帖最后由 毛毛猫猫 于 2015-4-19 20:05 编辑 ]