簡體   English   中英

使用掃描儀查找行尾?

[英]Using scanner to find the end of a line?

我正在使用掃描儀類將文本掃描到程序中,並且文本文件的每一行都是表單的預訂

(id) (month) (date) (numdays) (type1) (number1) (type2) (number2) . . .

預訂數據的前四個元素始終是相同的數字,即4,但是(type)和(number)數據可以具有任意數量的參數,因此我想檢測行尾是否有任何方法可以做到這一點與掃描儀類?

我想找到一行的結尾,因此我的代碼不會讀取下一行的預訂繼續記錄。

} else if(input.equals(“ Booking”)){

                int bookingId=inputStream.nextInt();
                System.out.printf("%d ",bookingId);
                String month = inputStream.next();
                System.out.printf("%s ", month);
                int date = inputStream.nextInt();
                System.out.printf("%d ", date);
                int numDays= inputStream.nextInt();
                System.out.printf("%d ", numDays);


                while(!(inputStream.findInLine("\n").equals("\n"))){
                   String nextType = inputStream.next();
                   System.out.printf("%s ",nextType);
                   int nextCapacity= inputStream.nextInt();
                   System.out.printf("%d ", nextCapacity);
                   Map<String, Integer> requests=new HashMap<String, Integer>(); 
                   requests.put(nextType,nextCapacity); 

                }

您可以檢查EOL:

charAt(i)!='\n' && charAt(i+1)!='\r'

或者您可能一次只讀整行:

 Scanner sc = new Scanner(file);

 line = sc.nextLine();

根據您的代碼,我建議使用兩種掃描儀:一種用於讀取整行,另一種用於讀取行中的符號。 這樣一來,第一台掃描儀就會解決EOL。 代碼如下所示:

Scanner sc = new Scanner(new File("input"));

while(sc.hasNextLine()) {
    Scanner scLine = new Scanner(sc.nextLine());

    int bookingId=scLine.nextInt();
    String month = scLine.next();
    int date = scLine.nextInt();
    int numDays= scLine.nextInt();

    System.out.printf("%d %s %d %d ", bookingId, month, date, numDays);

    Map<String, Integer> requests=new HashMap<>();
    while(scLine.hasNext()) {
        String type = scLine.next();
        int capacity= scLine.nextInt();
        requests.put(type, capacity);

        System.out.printf("%s %d", type, capacity);
    }

    System.out.println();
}

暫無
暫無

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

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