日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發布時間:2024/1/18 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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扫描器的简单使用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。