在 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP