在 Java 中使用 Scanner 物件作為方法引數的語法是什麼?
在 Java 1.5 之前,程式設計師需要依賴字元流類和位元組流類來讀取使用者資料。
從 Java 1.5 開始引入了 Scanner 類。此類接受 File、InputStream、Path 和 String 物件,使用正則表示式逐個讀取所有基本資料型別和字串(來自給定源)。
預設情況下,空格被視為分隔符(用於將資料分割成標記)。
要從源讀取各種資料型別,可以使用此類提供的 nextXXX() 方法,例如 nextInt()、nextShort()、nextFloat()、nextLong()、nextBigDecimal()、nextBigInteger()、nextLong()、nextShort()、nextDouble()、nextByte()、nextFloat()、next()。
將 Scanner 物件作為引數傳遞
您可以將 Scanner 物件作為引數傳遞給方法。
示例
以下 Java 程式演示瞭如何將 Scanner 物件傳遞給方法。此物件讀取檔案的內容。
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Scanner; public class ScannerExample { public String sampleMethod(Scanner sc){ StringBuffer sb = new StringBuffer(); while(sc.hasNext()) { sb.append(sc.nextLine()); } return sb.toString(); } public static void main(String args[]) throws IOException { //Instantiating the inputStream class InputStream stream = new FileInputStream("D:\sample.txt"); //Instantiating the Scanner class Scanner sc = new Scanner(stream); ScannerExample obj = new ScannerExample(); //Calling the method String result = obj.sampleMethod(sc); System.out.println("Contents of the file:"); System.out.println(result); } }
輸出
Contents of the file: Tutorials Point originated from the idea that there exists a class of readers who respond better to on-line content and prefer to learn new skills at their own pace from the comforts of their drawing rooms.
示例
在以下示例中,我們建立了一個 Scanner 物件,該物件以標準輸入 (System.in) 作為源,並將其作為引數傳遞給方法。
import java.io.IOException; import java.util.Scanner; public class ScannerExample { public void sampleMethod(Scanner sc){ StringBuffer sb = new StringBuffer(); System.out.println("Enter your name: "); String name = sc.next(); System.out.println("Enter your age: "); String age = sc.next(); System.out.println("Hello "+name+" You are "+age+" years old"); } public static void main(String args[]) throws IOException { //Instantiating the Scanner class Scanner sc = new Scanner(System.in); ScannerExample obj = new ScannerExample(); //Calling the method obj.sampleMethod(sc); } }
輸出
Enter your name: Krishna Enter your age: 25 Hello Krishna You are 25 years old
廣告