1. 程式人生 > 其它 >Scanner的輸入及理解

Scanner的輸入及理解

技術標籤:java字串

Scanner

new 新生的意思

System.out輸出

System.in 輸入

  • Scannery物件

  • 基本語法:

    Scanner s = new Scanner(System.in);
    
  • 通過Scanner類的next(下一個)與nextline(下一行)方法獲取輸入的字串,在讀取前我們一般需要使用hasNext()與hasNextline()判斷是否還有輸入的資料。

package Scnner;

import java.util.Scanner;

public class Day01 {
	
	public static void main
(String[] args) { //建立一個掃描物件,用於接收鍵盤資料 Scanner scanner = new Scanner(System.in); //接收使用者的輸入,並把它封裝scanner System.out.println("使用next方式接收:"); //判斷使用者有沒有輸出字串 if (scanner.hasNext()==true) { //這裡預設==true,不用謝也可以,但是還是建議寫 String str = scanner.next(); //使用next方式接收 System.
out.println("輸出的內容為:"+str); } } }
  1. next()
  • 一定要讀取到有效字元後才可以結束輸入。
  • 對輸入有效字元之前遇到的空白,next()方法會自動將其去掉。
  • 只有輸入有效字元後才將其後面輸入的空白作為分隔符或者借宿符。
  • next()不能得到帶有空格的字串
  1. nextLine():

    • 以enter為結束符,也就是說nextLine()方法返回的輸入回車之前的所有字元。

    • 可以獲得空白

      package Scnner;
      
      import java.util.Scanner;
      
      public class Day02 {
      	
      	
      	public static
      void main(String[] args) { //從鍵盤來接收資料 Scanner scanner = new Scanner(System.in); System.out.println("使用nextLine方式接收:"); //判斷是否還有輸入 if (scanner.hasNextLine()){ //等待使用者去輸入 String str = scanner.nextLine(); System.out.println("輸出的內容:"+str); } scanner.close(); } }

當然也可以不要if去判斷

if (scanner.hasNextLine())
package Scnner;

import java.util.Scanner;

public class Day03 {

	public static void main(String[] args) {
		
	Scanner scanner = new Scanner(System.in);	
		System.out.println("請輸入資料:");
		String str = scanner.nextLine();
		System.out.println("輸出的內容:"+str);
		
		
		scanner.close();
		
		
	}

這樣也是可以的

Scanner輸入內容理解(重點)

我個人是這樣理解的

輸入輸出我們只要記住3行程式碼就行

System.out.println("請輸入資料:");
		String str = scanner.nextLine();
		System.out.println("輸出的內容:"+str);

第一行程式碼是標題

請輸入資料:

第二行程式碼: 是我們鍵盤所輸出的所有內容,知道你按下回車鍵(enter)之後,把所有內容變成一個變數儲存再str裡面

第三行程式碼:則是等待第二行程式碼執行完成後,將輸出內容+str(你鍵盤敲下的所有字元,也就是內容) 一起顯示出來

如下圖

在這裡插入圖片描述

第一行為第一行程式碼

第二行hello world 為第二行程式碼,也就是你鍵盤敲下的內容

第三行則是等待第二行程式碼執行完成後,輸出的內衣+鍵盤敲下的所有字元一起顯示出來

注意

//凡是IO流的類如果不關閉會一直佔用資源,要養成好習慣用完就關掉
		scanner.close();
		//IO流 輸入輸出流