java 0.7 使用者互動物件Scanner
阿新 • • 發佈:2022-03-16
使用者互動物件Scanner的使用
1.Scanner簡介
java.until.Scanner是java5的新特徵,我們可以通過Scanner類來獲取使用者的輸出.
2.基本語法:
Scanner s = new Scanner(System.in);
3.常見接收方式:
1.next
``
public class Test000 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);//建立一個scanner物件,用來接收鍵盤資料。 System.out.println("使用next方式接收:"); if (scanner.hasNext()){ String str = scanner.next(); System.out.println("輸出內容為"+str); } scanner.close();//關閉scanner }}
控制檯輸出如下:
使用next方式接收:
hello world
輸出內容為hello注意: 1. 對輸入有效字元前遇到的空白,next()方法會自動將其去掉.
2. next()不能得到帶有空格的字串.
3.只有輸入有效字元後才將其後面輸出的空白作為分隔符或者結束符.
2.nextLine():
``
import java.util.Scanner; public class Test000 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);//建立一個scanner物件,用來接收鍵盤資料。 System.out.println("使用nextLine方式接收:"); if (scanner.hasNextLine()){ String str = scanner.nextLine(); System.out.println("輸出內容為"+str); } scanner.close(); }}
控制檯輸出如下:
使用nextLine方式接收:
hello world
輸出內容為hello world注意:1.nextLine()以enter未結束符,nextLine()返回的是輸入回車之前的所有字元。
2.可以獲得空白
4.應用
``
import java.util.Scanner; public class Test001 { public static void main(String[] args) { Scanner scanner= new Scanner(System.in); System.out.println("請輸入你的姓名:"); String str= scanner.next();//使用next接受資料並賦值給str //如果輸入的值等於"王"或者"wang"則輸出yyds否則輸出"小傻瓜" if (str.equals("王")||str.equals("wang")){ System.out.println("yyds"); } else{ System.out.println("小傻瓜"); } scanner.close(); } }