java scanner对象_使用Java的方法中将Scanner对象作为参数传递的语法是什么?

直到Java 1.5从用户程序员那里读取数据之前,都依赖于字符流类和字节流类。

从Java 1.5开始引入Scanner类。此类接受File,InputStream,Path和String对象,使用正则表达式逐个令牌读取所有原始数据类型和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 {

//实例化inputStream类

InputStream stream = new FileInputStream("D:\\sample.txt");

//实例化Scanner类

Scanner sc = new Scanner(stream);

ScannerExample obj = new ScannerExample();

//调用方法

String result = obj.sampleMethod(sc);

System.out.println("文件内容:");

System.out.println(result);

}

}

输出结果文件内容:

nhooo.com 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.

示例

在下面的示例中,我们创建一个具有标准输入(System.in)作为源的Scanner对象,并将其作为参数传递给方法。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 {

//实例化Scanner类

Scanner sc = new Scanner(System.in);

ScannerExample obj = new ScannerExample();

//调用方法

obj.sampleMethod(sc);

}

}

输出结果Enter your name:

Krishna

Enter your age:

25

Hello Krishna You are 25 years old

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值