ublic class BoxOfProduce {
private static String Item1;
private static String Item2;
private static String Item3;
/**
* 用来随机抽取文件内的水果名称,并且复制给Lineread
*
* @return Lineread
* @throws IOException
*/
private String randomlySelect() throws IOException {
int Linenum;
String Lineread = null;
// 创建Random类,随机生成0~4之间的一个数
Random rd = new Random();
Linenum = rd.nextInt(5);
// 打开文件
File file = new File("itemList.txt");
Scanner inputFile = new Scanner(file);
// 用for循环给Lineread赋值
for (int i = 0; i <= Linenum; i++) {
Lineread = inputFile.nextLine();
}
// 关闭文件
inputFile.close();
// 返回Lineread
return Lineread;
}
/**
* 创建一个constructor,给Item1,Item2,Item3赋值
*
* @throws IOException
*/
public BoxOfProduce() throws IOException {
Item1 = randomlySelect();
Item2 = randomlySelect();
Item3 = randomlySelect();
}
/**
* 用来返回Item1
*
* @return Item1
*/
public static String getItem1() {
return Item1;
}
/**
* 可以用来改变Item1的值
*
* @param item1
*/
public static void setItem1(String item1) {
Item1 = item1;
}
/**
* 用来返回Item2
*
* @return Item2
*/
public static String getItem2() {
return Item2;
}
/**
* 可以用来改变Item2的值
*
* @param item2
*/
public static void setItem2(String item2) {
Item2 = item2;
}
/**
* 用来返回Item3
*
* @return Item3
*/
public static String getItem3() {
return Item3;
}
/**
* 可以用来改变Item3的值
*
* @param item3
*/
public static void setItem3(String item3) {
Item3 = item3;
}
/**
* 输出Item1,Item2,Item3的值
*/
public void display() {
System.out.println("The contents of the box:");
System.out.println("Item1:" + Item1);
System.out.println("Item2:" + Item2);
System.out.println("Item3:" + Item3);
System.out.println();
}
public static void main(String[] args) throws IOException {
String answer; //用来得到用户的答案
String substituteItem;//用户输入的用来替换的水果名称
//创建Scanner类
Scanner kb = new Scanner(System.in);
//创建BoxOfProduce类
BoxOfProduce boxOfProduce = new BoxOfProduce();
boxOfProduce.display();
//询问用户是否满意第一种水果
System.out.print("Do you agree with the selected item1,"
+ boxOfProduce.getItem1() + "(Yes or No):");
answer = kb.nextLine();
if (answer.equals("No")) {
System.out
.print("Enter the substituting fruit or vegetable for item1:");
//得到替换水果的名称
substituteItem = kb.nextLine();
boxOfProduce.setItem1(substituteItem);
}
System.out.print("Do you agree with the selected item2,"
+ boxOfProduce.getItem2() + "(Yes or No):");
answer = kb.nextLine();
if (answer.equals("No")) {
System.out
.print("Enter the substituting fruit or vegetable for item2:");
substituteItem = kb.nextLine();
boxOfProduce.setItem2(substituteItem);
}
System.out.print("Do you agree with the selected item3,"
+ boxOfProduce.getItem3() + "(Yes or No):");
answer = kb.nextLine();
if (answer.equals("No")) {
System.out
.print("Enter the substituting fruit or vegetable for item3:");
substituteItem = kb.nextLine();
boxOfProduce.setItem3(substituteItem);
}
System.out.println();
//输出最终结果
boxOfProduce.display();
}
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70007877/viewspace-2837592/ ,如需转载,请注明出处,否则将追究法律责任。