CodeGym/Java Blog/Toto sisi/Java 掃描器類
John Squirrels
等級 41
San Francisco

Java 掃描器類

在 Toto sisi 群組發布
個成員
你好!我們今天的課會很特別!在今天的課程中,我們將討論 Java Scanner 類。以前,完成任務和編寫程序的過程很簡單:我們編寫一些代碼,運行 main ()方法,程序執行所需的操作,我們就完成了。但現在一切都將改變!今天我們將學習如何與程序真正互動:我們將教它如何對我們的行為做出反應!在我們開始分析代碼之前,您是否曾經與掃描儀之類的設備打交道?大概。掃描儀的內部非常複雜,但其工作原理非常簡單:它讀取用戶提供的數據(例如護照或保險單)並將這些信息存儲在內存中(例如,作為圖像). 今天您將創建自己的掃描儀!當然,它不能處理紙質文檔,但文本對它來說沒有問題:) 走吧!

Java的掃描器類

掃描儀類 - 1首先,我們必須熟悉java.util.Scanner類。它的功能非常簡單。與真正的掃描儀一樣,它從您指定的來源讀取數據。比如一個字符串,一個文件,控制台。接下來,它識別信息並適當地處理它。這是最簡單的例子:
public class Main {

   public static void main(String[] args) {

       Scanner scanner = new Scanner("It matters not how strait the gate,\n" +
               "How charged with punishments the scroll,\n" +
               "I am the master of my fate,\n" +
               "I am the captain of my soul");
       String s = scanner.nextLine();
       System.out.println(s);
   }
}
我們創建了一個掃描儀對象,並指定了它的數據源(一串文本)。nextLine ()方法訪問數據源(帶有絕句的文本),找到下一個未讀行(在本例中為第一行),並返回它。然後我們在控制台上顯示: 控制台輸出:
It matters not how strait the gate,
我們可以多次 使用nextLine()方法並顯示整首詩的摘錄:
public class Main {

   public static void main(String[] args) {

       Scanner scanner = new Scanner("It matters not how strait the gate,\n" +
               "How charged with punishments the scroll,\n" +
               "I am the master of my fate,\n" +
               "I am the captain of my soul");
       String s = scanner.nextLine();
       System.out.println(s);
       s = scanner.nextLine();
       System.out.println(s);
       s = scanner.nextLine();
       System.out.println(s);
       s = scanner.nextLine();
       System.out.println(s);
   }
}
每次,我們的掃描儀都會向前邁出一步並讀取下一行。顯示程序的輸出:
It matters not how strait the gate,
How charged with punishments the scroll,
I am the master of my fate,
I am the captain of my soul
正如我們已經說過的,掃描器的數據源不一定是字符串。例如,它可能是控制台。一些令人振奮的消息:以前,我們只是在那裡顯示數據,但現在我們將從鍵盤讀取數據!讓我們看看Scanner類還做了什麼:
public class Main {

   public static void main(String[] args) {

       Scanner sc = new Scanner(System.in);
       System.out.println("Enter a number:");

       int number = sc.nextInt();

       System.out.println("Thanks! You entered the number " + number);

   }
}
nextInt ()方法讀取並返回輸入的數字。在我們的程序中,我們使用它為變量number賦值。它已經更像是一台真正的掃描儀了!該程序要求用戶輸入任何數字。用戶完成此操作後,程序會感謝用戶,顯示結果,然後結束。但是我們還有一個嚴重的問題。用戶可能會犯錯誤並輸入錯誤的內容。 這是我們當前程序停止工作的示例:
public class Main {

   public static void main(String[] args) {

       Scanner sc = new Scanner(System.in);
       System.out.println("Enter a number:");

       int number = sc.nextInt();

       System.out.println("Thanks! You entered the number " + number);

   }
}
讓我們嘗試輸入字符串“CodeGym”而不是數字:控制台輸出:
Enter a number:
CodeGym
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Main.main(Main.java:10) Process finished with exit code 1
呃,哦。我們有大麻煩了 -_- 為了避免這種情況,我們需要想出一種方法來驗證用戶輸入的數據。例如,如果用戶輸入的不是數字,最好顯示一條警告,提示輸入的信息不是數字。如果信息沒問題,那麼我們可以確認。但這需要我們“展望未來”,看看我們的流中會發生什麼。掃描儀可以做到這一點嗎?如何!它有很多方法可以執行此操作: hasNextInt() — 此方法檢查下一個輸入數據塊是否為數字(根據需要返回 true 或 false)。 hasNextLine() — 此方法檢查下一個輸入塊是否為字符串。 有下一個字節()hasNextShort()hasNextLong()hasNextFloat()hasNextDouble() — 所有這些方法都對其餘數據類型執行類似的檢查。讓我們嘗試改變我們的數字閱讀程序:
public class Main {

   public static void main(String[] args) {

       Scanner sc = new Scanner(System.in);
       System.out.println("Enter a number:");

       if (sc.hasNextInt()) {
           int number = sc.nextInt();
           System.out.println("Thanks! You entered the number " + number);
       } else {
           System.out.println("Sorry, but this is clearly not a number. Restart the program and try again!");
       }

   }
}
現在我們的程序檢查下一個輸入的字符是否是數字。並且它僅在確認時顯示確認。如果輸入未通過檢查,程序會記錄下來並要求用戶重試。基本上,您可以與Scanner對象進行通信,並提前找出等待您的數據類型。數字、字符串或其他內容?一個號碼?什麼樣的?一個intshortlong?” 這種靈活性使您有機會構建取決於用戶行為的程序邏輯。我們應該注意另一個重要的方法:useDelimiter()。您將一個字符串傳遞給該方法。該字符串包含要用作分隔符或定界符的字符。 例如,假設我們突然對日本詩歌產生了興趣,並決定用我們的掃描儀閱讀大詩人松尾芭蕉寫的一些俳句。即使將三個不同的詩句作為一個笨拙的字符串傳遞給我們,我們也可以輕鬆地將它們拆分並精美地渲染它們:
public class Main {
   public static void main(String[] args) {
       Scanner scan = new Scanner("On a withered branch'" +
               "A crow has alighted.'" +
               "Nightfall in autumn." +
               "''***''" +
               "Such a moon above,'" +
               "Like a tree cut at the root:'" +
               "he fresh cut is white." +
               "''***''" +
               "How the river floods!'" +
               "A heron wanders on short legs,'" +
               "Knee-deep in the water.");

       scan.useDelimiter("'");

       while (scan.hasNext()) {
           System.out.println(scan.next());
       }

       scan.close();
   }
}
我們使用“\ n /*/*/*”(換行符和三個星號)作為分隔符。結果,我們得到了漂亮的控制台輸出,就像書中一樣:
On a withered branch
A crow has alighted.
Nightfall in autumn.

***

Such a moon above,
Like a tree cut at the root:
The fresh cut is white.

***

How the river floods!
A heron wanders on short legs,
Knee-deep in the water.
這個例子還有一個我們必須絕對指出的方法: close()。與任何使用 I/O 流的對像一樣,掃描器在完成後必須關閉,以停止消耗計算機資源。永遠不要忘記close()方法!
public class Main {

   public static void main(String[] args) {

       Scanner sc = new Scanner(System.in);
       System.out.println("Enter a number:");

       int number = sc.nextInt();

       System.out.println("Thanks! You entered the number " + number);

       sc.close(); // Now we've done everything right!

   }
}
就是這樣!如您所見,Scanner類非常容易使用,這很有幫助!:) 為了鞏固您所學的知識,我們建議您觀看我們的 Java 課程中的視頻課程
留言
  • 受歡迎
你必須登入才能留言
此頁面尚無留言