用java保存扫描仪的输入



我需要保存从扫描仪输入中收集的数据,以便在整个代码中再次使用。例如,如果有人输入了值1,它会被保存到数组中,然后他们输入了值2,这两个值都应该被保存到阵列中。

这是我到目前为止的代码:


public static void main(String[] args){

Scanner myObj = new Scanner(System.in);
System.out.println("Enter the customer name, the day of the booking, the month of the booking, and the number of people:");
String name = myObj.nextLine();
int day = myObj.nextInt();
int month = myObj.nextInt();
int number = myObj.nextInt();

int y = day;
int x = month;
if (y > 21 && x > 03) { 
System.out.println("Upcoming bookings: ");
System.out.println("Customer name: " + name); 
System.out.println("Date of booking: " + day + "/" + month);
System.out.println("Number of People: " + number); 
}
else {
System.out.println("There are no upcoming bookings");
}
}

其想法是,用户可以输入预订详细信息,但只有在日期尚未过去时才会显示,因此,我需要能够保存扫描仪收集的所有输入。

我不会写整个代码,但会给你一些想法,让你可以处理它。你需要创建一个类,你可以将其命名为Booking

class Booking {
public String name;
public int day;
public int month;
public int number;

public Booking(Scanner sc) {
System.out.println("Enter the customer name, the day of the booking, the month of the booking, and the number of people:");
this.name = sc.nextLine();
.....
}

public boolean validDate(int month, int year){
if(this.month < month && this.year < year)
return false;
return true;
}     
}

class Main(){ 

List<Booking> objLst = new ArrayList<Booking>();

public static void main (String[] args){
Scanner sc = new Scanner(System.in);


Booking booking1 = new Booking(sc);
objLst.add(booking1);
Booking booking2 = new Booking(sc);
objLst.add(booking2);
for (int i = 0; i < objLst.size(); i++) {
if(objLst.get(i).validDate(22, 2021){
//Create print function in Booking class and call it here.
}
}
//and booking.validDate will return true or false to check if date is not passed
}

}

对于这些数据,您可以声明类,并可以使用对象数组来存储所有输入。但对于if条件,您需要迭代数组中存储的所有数据

如果保存是指";您可以在终止程序"之后再次检索数据;那么您可能想要查看Java文件处理或Java数据库连接。如果你不想要数据库的方法,我建议你尝试文件处理,也可以看看我一年前的问题。我创建了一个正常工作的保存文件,但您需要将数据存储在对象的数组列表中(请参阅@Syed Mohib Uddin的回答(。

最新更新