Java 自學筆記-基本文法2-從控制台接收輸入字元及scanner.nextLine

來源:互聯網
上載者:User

標籤:

Scanner 類封裝了輸入資料流對象,並使用nextLine()方法輸入資料流中擷取使用者輸入的整行文本字元

package hahaa;

import java.util.Scanner;

public class ha {
public static void main (String[] args) {
Scanner scanner =new Scanner(System.in);
System.out.println("請輸入你的想輸入的數字");

String line = scanner.nextLine();
System.out.println("輸出數位長度"+line.length());

}

}

 

控制台

請輸入你的想輸入的數字
2315348
輸出數位長度7

 

 

 

 

 

next()一定要讀取到有效字元後才可以結束輸入,對輸入有效字元之前遇到的空格鍵、Tab鍵或Enter鍵等結束符,next()方法會自動將其去掉,只有在輸入有效字元之後,next()方法才將其後輸入的空格鍵、Tab鍵或Enter鍵等視為分隔字元或結束符。簡單地說,next()尋找並返回來自此掃描器的下一個完整標記。完整標記的前後是與分隔模式比對的輸入資訊,所以next方法不能得到帶空格的字串。 而nextLine()方法的結束符只是Enter鍵,即nextLine()方法返回的是Enter鍵之前的所有字元,它是可以得到帶空格的字串的。

在每一個 next()、nextDouble()  、 nextFloat()、nextInt() 等語句之後加一個nextLine()語句,將被next()會去掉空格包括空格後的文字,直到Enter後輸入的文字才有效。

主函數(有借鑒)
public static void main(String[] args) {

String s1,s2;
Scanner sc=new Scanner(System.in);
System.out.print("請輸入第一個字串:");
s1=sc.next();
sc.nextLine();
System.out.print("請輸入第二個字串:");
s2=sc.next();
System.out.println("輸入的字串是:"+s1+" "+s2);
}

 

控制台 ----

請輸入第一個字串:woini dasdasfa
請輸入第二個字串:adsdfsdasd
輸入的字串是:woini adsdfs

Java 自學筆記-基本文法2-從控制台接收輸入字元及scanner.nextLine

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.