java基础之Scanner扫描器的简单使用
生活随笔
收集整理的這篇文章主要介紹了
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扫描器的简单使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 开源堡垒机Guacamole二次开发记录
- 下一篇: IDL语言.dat文件转.tiff