欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

java基础之Scanner扫描器的简单使用

发布时间:2024/1/18 41 豆豆
生活随笔 收集整理的这篇文章主要介绍了 java基础之Scanner扫描器的简单使用 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

案例一:

import java.util.Scanner;/*** 接收字符串*/ public class Test1 {public static void main(String[] args) {//创建一个扫描器对象,用于接收键盘数据Scanner scanner = new Scanner(System.in);System.out.println("使用next方式接收:");//判断用户有没有输入字符串if (scanner.hasNext()) {//使用next方式接收String s = scanner.next();System.out.println(s);}//IO流的类用完一定要关闭scanner.close();} }

案例二:

import java.util.Scanner;/*** 接收字符串*/ public class Test2 {public static void main(String[] args) {//创建一个扫描器对象,用于接收键盘数据Scanner scanner = new Scanner(System.in);System.out.println("使用nextLine方式接收:");//判断用户有没有输入字符串if (scanner.hasNextLine()){//使用nextLine方式接收String s = scanner.nextLine();System.out.println(s);}//IO流的类用完一定要关闭scanner.close();} }

案例三:

import java.util.Scanner;/*** 接收整型数据*/ public class Test3 {public static void main(String[] args) {//创建一个扫描器对象,用于接收键盘数据Scanner scanner = new Scanner(System.in);System.out.println("使用nextInt方式接收:");if (scanner.hasNextInt()){//使用nextInt方式接收int a = scanner.nextInt();int b = a + 2;System.out.println(b);}else {System.out.println("你输入的不是int型数据");}//IO流的类用完一定要关闭scanner.close();} }

注意:next()不能得到带有空格的字符串,nextLine()可以。因此nextLine()用得较多。

案例4:文件的输出和输入

import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.nio.file.Paths; import java.util.Scanner;public class Test {public static void main(String[] args) {/*** 文件输出*/try {Scanner scanner = new Scanner(Paths.get("D:\\data\\tt.txt"), "UTF-8");//判断用户有没有输入字符串while (scanner.hasNextLine()){//使用nextLine方式接收String s = scanner.nextLine();System.out.println(s);}//IO流的类用完一定要关闭scanner.close();} catch (IOException e) {e.printStackTrace();}/*** 文件输入*/try {PrintWriter printWriter = new PrintWriter("D:\\data\\tt.txt", "UTF-8");//写入字符串到tt.txt中printWriter.print("写入文件测试");printWriter.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();}} }

总结

以上是生活随笔为你收集整理的java基础之Scanner扫描器的简单使用的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。