簡體   English   中英

在 java 中保存來自掃描儀的輸入

[英]Saving inputs from scanner in 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");
   }

}

這個想法是用戶可以輸入預訂詳細信息,但只有在日期尚未過去時才會顯示,但是,我需要能夠保存掃描儀收集的所有輸入。

我不會編寫整個代碼,但會給你一些想法,以便你可以處理它。 您需要創建一個 class 您可以將其命名為 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
    }

}

對於這些數據,您可以聲明 class 並可以使用 object 的數組來存儲所有輸入。 但是對於 if 條件,您需要迭代存儲在數組中的所有數據

如果保存的意思是“您可以在終止程序后再次檢索數據”,那么您可能需要查看Java 文件處理Java 數據庫連接 如果您不想要數據庫方法,我建議您嘗試文件處理,也可以查看我一年前的問題 我創建了一個功能正常的保存文件,但您需要將數據存儲在對象的 arraylist 中(請參閱@Syed Mohib Uddin 答案)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM