1. 程式人生 > >Scanner類概述及其構造方法

Scanner類概述及其構造方法

名稱格式day天數_scanner

Scanner類概述及其構造方法

Scanner類概述

   JDK5以後用於獲取使用者的鍵盤輸入

構造方法

   public Scanner(InputStream source)

基本格式

    hasNextXxx()  判斷是否還有下一個輸入項,其中Xxx可以是Int,Double等。如果需要判斷是否包含下一個字串,則可以省略Xxx

     nextXxx()  獲取下一個輸入項。Xxx的含義和上個方法中的Xxx相同

預設情況下,Scanner使用空格,回車等作為分隔符

常用方法

   public int nextInt()

   public String nextLine()

package cn.it18zhang_01;

/*

 * Scanner:用於接收鍵盤錄入資料。

 *

 * 前面的時候:

 * A:導包

 * B:建立物件

 * C:呼叫方法

 *

 * System類下有一個靜態的欄位:

 * public static final InputStream in; 標準的輸入流,對應著鍵盤錄入。

 *

 * InputStream is = System.in;

 *

 * class Demo {

 * public static final int x = 10;

 * public static final Student s = new Student();

 * }

 * int y = Demo.x;

 * Student s = Demo.s;

 *

 *

 * 構造方法:

 * Scanner(InputStream source)

 */

import java.util.Scanner;

public class ScannerDemo {

public static void main(String[] args) {

// 建立物件

Scanner sc = new Scanner(System.in);

int x = sc.nextInt();

System.out.println("x:" + x);

}

}

案例二

package cn.itcast_02;

import java.util.Scanner;

/*

 * 基本格式:

 * public boolean hasNextXxx():判斷是否是某種型別的元素

 * public Xxx nextXxx():獲取該元素

 *

 * 舉例:用int型別的方法舉例

 * public boolean hasNextInt()

 * public int nextInt()

 *

 * 注意:

 * InputMismatchException:輸入的和你想要的不匹配

 */

public class ScannerDemo {

public static void main(String[] args) {

// 建立物件

Scanner sc = new Scanner(System.in);

// 獲取資料

if (sc.hasNextInt()) {

int x = sc.nextInt();

System.out.println("x:" + x);

} else {

System.out.println("你輸入的資料有誤");

}

}

}

String類概述及其構造方法

字串是由多個字元組成的一串資料(字元序列)

字串可以看成是字元陣列

構造方法

public String()

public String(byte[] bytes)

public String(byte[] bytes,int offset,int length)

public String(char[] value)

public String(char[] value,int offset,int count)

public String(String original)

package com.it18zhang_01;

/*

 * 字串:就是由多個字元組成的一串資料。也可以看成是一個字元陣列。

 * 通過檢視API,我們可以知道

 * A:字串字面值"abc"也可以看成是一個字串物件。

 * B:字串是常量,一旦被賦值,就不能被改變。

 *

 * 構造方法:

 * public String():空構造

 *public String(byte[] bytes):把位元組陣列轉成字串

 *public String(byte[] bytes,int index,int length):把位元組陣列的一部分轉成字串

 *public String(char[] value):把字元陣列轉成字串

 *public String(char[] value,int index,int count):把字元陣列的一部分轉成字串

 *public String(String original):把字串常量值轉成字串

 *

 * 字串的方法:

 * public int length():返回此字串的長度。

 */

public class StringDemo {

public static void main(String[] args) {

// public String():空構造

String s1 = new String();

System.out.println("s1:" + s1);

System.out.println("s1.length():" + s1.length());

System.out.println("--------------------------");

// public String(byte[] bytes):把位元組陣列轉成字串

byte[] bys = { 97, 98, 99, 100, 101 };

String s2 = new String(bys);

System.out.println("s2:" + s2);

System.out.println("s2.length():" + s2.length());

System.out.println("--------------------------");

// public String(byte[] bytes,int index,int length):把位元組陣列的一部分轉成字串

// 我想得到字串"bcd"

String s3 = new String(bys, 1, 3);

System.out.println("s3:" + s3);

System.out.println("s3.length():" + s3.length());

System.out.println("--------------------------");

// public String(char[] value):把字元陣列轉成字串

char[] chs = { 'a', 'b', 'c', 'd', 'e', '', '', '' };

String s4 = new String(chs);

System.out.println("s4:" + s4);

System.out.println("s4.length():" + s4.length());

System.out.println("--------------------------");

// public String(char[] value,int index,int count):把字元陣列的一部分轉成字串

String s5 = new String(chs, 2, 4);

System.out.println("s5:" + s5);

System.out.println("s5.length():" + s5.length());

System.out.println("--------------------------");

//public String(String original):把字串常量值轉成字串

String s6 = new String("abcde");

System.out.println("s6:" + s6);

System.out.println("s6.length():" + s6.length());

System.out.println("--------------------------");

//字串字面值"abc"也可以看成是一個字串物件。

String s7 = "abcde";

System.out.println("s7:"+s7);

System.out.println("s7.length():"+s7.length());

}

}

String類的特點

字串是常量,它的值在建立之後不能更改

String s = hello; s += world; s的結果是多少?

package cn.it18zhang_02;

/*

 * 字串的特點:一旦被賦值,就不能改變。

 */

public class StringDemo {

public static void main(String[] args) {

String s = "hello";

s += "world";

System.out.println("s:" + s); // helloworld

}

}

原理圖:

 

面試題

String s = new String(hello)String s = hello;的區別?

package cn.it18zhang_02;

/*

 * String s = new String(hello)String s = hello;的區別?

 * 有。前者會建立2個物件,後者建立1個物件。

 *

 * ==:比較引用型別比較的是地址值是否相同

 * equals:比較引用型別預設也是比較地址值是否相同,而String類重寫了equals()方法,比較的是內容是否相同。

 */

public class StringDemo2 {

public static void main(String[] args) {

String s1 = new String("hello");

String s2 = "hello";

System.out.println(s1 == s2);// false

System.out.println(s1.equals(s2));// true

}

}

 

面試題:

package cn.it18zhang_02;

/*

 * 看程式寫結果

 */

public class StringDemo3 {

public static void main(String[] args) {

String s1 = new String("hello");

String s2 = new String("hello");

System.out.println(s1 == s2);// false

System.out.println(s1.equals(s2));// true

String s3 = new String("hello");

String s4 = "hello";

System.out.println(s3 == s4);// false

System.out.println(s3.equals(s4));// true

String s5 = "hello";

String s6 = "hello";

System.out.println(s5 == s6);// true

System.out.println(s5.equals(s6));// true

}

}

面試題二:

package cn.it18zhang_02;

/*

 * 看程式寫結果

 * 字串如果是變數相加,先開空間,在拼接。

 * 字串如果是常量相加,是先加,然後在常量池找,如果有就直接返回,否則,就建立。

 */

public class StringDemo4 {

public static void main(String[] args) {

String s1 = "hello";

String s2 = "world";

String s3 = "helloworld";

System.out.println(s3 == s1 + s2);// false

System.out.println(s3.equals((s1 + s2)));// true

System.out.println(s3 == "hello" + "world");// false 這個我們錯了,應該是true

System.out.println(s3.equals("hello" + "world"));// true

// 通過反編譯看原始碼,我們知道這裡已經做好了處理。

// System.out.println(s3 == "helloworld");

// System.out.println(s3.equals("helloworld"));

}

}

String類的判斷功能

boolean equals(Object obj)

boolean equalsIgnoreCase(String str)

boolean contains(String str)

boolean startsWith(String str)

boolean endsWith(String str)

boolean isEmpty()

package cn.it18zhang_03;

/*

 * String類的判斷功能:

 * boolean equals(Object obj):比較字串的內容是否相同,區分大小寫

 * boolean equalsIgnoreCase(String str):比較字串的內容是否相同,忽略大小寫

 * boolean contains(String str):判斷大字串中是否包含小字串

 * boolean startsWith(String str):判斷字串是否以某個指定的字串開頭

 * boolean endsWith(String str):判斷字串是否以某個指定的字串結尾

 * boolean isEmpty():判斷字串是否為空。

 *

 * 注意:

 * 字串內容為空和字串物件為空。

 * String s = "";

 * String s = null;

 */

public class StringDemo {

public static void main(String[] args) {

// 建立字串物件

String s1 = "helloworld";

String s2 = "helloworld";

String s3 = "HelloWorld";

// boolean equals(Object obj):比較字串的內容是否相同,區分大小寫

System.out.println("equals:" + s1.equals(s2));

System.out.println("equals:" + s1.equals(s3));

System.out.println("-----------------------");

// boolean equalsIgnoreCase(String str):比較字串的內容是否相同,忽略大小寫

System.out.println("equals:" + s1.equalsIgnoreCase(s2));

System.out.println("equals:" + s1.equalsIgnoreCase(s3));

System.out.println("-----------------------");

// boolean contains(String str):判斷大字串中是否包含小字串

System.out.println("contains:" + s1.contains("hello"));

System.out.println("contains:" + s1.contains("hw"));

System.out.println("-----------------------");

// boolean startsWith(String str):判斷字串是否以某個指定的字串開頭

System.out.println("startsWith:" + s1.startsWith("h"));

System.out.println("startsWith:" + s1.startsWith("hello"));

System.out.println("startsWith:" + s1.startsWith("world"));

System.out.println("-----------------------");

// 練習:boolean endsWith(String str):判斷字串是否以某個指定的字串結尾這個自己玩

// boolean isEmpty():判斷字串是否為空。

System.out.println("isEmpty:" + s1.isEmpty());

String s4 = "";

String s5 = null;

System.out.println("isEmpty:" + s4.isEmpty());

// NullPointerException

// s5物件都不存在,所以不能呼叫方法,空指標異常

System.out.println("isEmpty:" + s5.isEmpty());

}

}

模擬登入,給三次機會,並提示還有幾次。

package cn.it18zhang_03;

import java.util.Scanner;

/*

 * 模擬登入,給三次機會,並提示還有幾次。如果登入成功,就可以玩猜數字小遊戲了。

 *

 * 分析:

 * A:定義使用者名稱和密碼。已存在的。

 * B:鍵盤錄入使用者名稱和密碼。

 * C:比較使用者名稱和密碼。

 * 如果都相同,則登入成功

 * 如果有一個不同,則登入失敗

 * D:給三次機會,用迴圈改進,最好用for迴圈。

 */

public class StringTest2 {

public static void main(String[] args) {

// 定義使用者名稱和密碼。已存在的。

String username = "admin";

String password = "admin";

// 給三次機會,用迴圈改進,最好用for迴圈。

for (int x = 0; x < 3; x++) {

// x=0,1,2

// 鍵盤錄入使用者名稱和密碼。

Scanner sc = new Scanner(System.in);

System.out.println("請輸入使用者名稱:");

String name = sc.nextLine();

System.out.println("請輸入密碼:");

String pwd = sc.nextLine();

// 比較使用者名稱和密碼。

if (name.equals(username) && pwd.equals(password)) {

// 如果都相同,則登入成功

System.out.println("登入成功,開始玩遊戲");

//猜數字遊戲

GuessNumberGame.start();

break;

} else {

// 如果有一個不同,則登入失敗

// 2,1,0

// 如果是第0次,應該換一種提示

if ((2 - x) == 0) {

System.out.println("帳號被鎖定,請與班長聯絡");

} else {

System.out.println("登入失敗,你還有" + (2 - x) + "次機會");

}

}

}

}

}

package cn.it18zhang_03;

import java.util.Scanner;

/*

 * 這時猜數字小遊戲的程式碼

 */

public class GuessNumberGame {

private GuessNumberGame() {

}

public static void start() {

// 產生一個隨機數

int number = (int) (Math.random() * 100) + 1;

while (true) {

// 鍵盤錄入資料

Scanner sc = new Scanner(System.in);

System.out.println("請輸入你要猜的資料(1-100)");

int guessNumber = sc.nextInt();

// 判斷

if (guessNumber > number) {

System.out.println("你猜的資料" + guessNumber + "大了");

} else if (guessNumber < number) {

System.out.println("你猜的資料" + guessNumber + "小了");

} else {

System.out.println("恭喜你,猜中了");

break;

}

}

}

}

String類的獲取功能

int length()

char charAt(int index)

int indexOf(int ch)

int indexOf(String str)

int indexOf(int ch,int fromIndex)

int indexOf(String str,int fromIndex)

String substring(int start)

String substring(int start,int end)

案例:

package cn.it18zhang_04;

/*

 * String類的獲取功能

 * int length():獲取字串的長度。

 * char charAt(int index):獲取指定索引位置的字元

 * int indexOf(int ch):返回指定字元在此字串中第一次出現處的索引。

 * 為什麼這裡是int型別,而不是char型別?

 * 原因是:'a'97其實都可以代表'a'

 * int indexOf(String str):返回指定字串在此字串中第一次出現處的索引。

 * int indexOf(int ch,int fromIndex):返回指定字元在此字串中從指定位置後第一次出現處的索引。

 * int indexOf(String str,int fromIndex):返回指定字串在此字串中從指定位置後第一次出現處的索引。

 * String substring(int start):從指定位置開始擷取字串,預設到末尾。

 * String substring(int start,int end):從指定位置開始到指定位置結束擷取字串。

 */

public class StringDemo {

public static void main(String[] args) {

// 定義一個字串物件

String s = "helloworld";

// int length():獲取字串的長度。

System.out.println("s.length:" + s.length());

System.out.println("----------------------");

// char charAt(int index):獲取指定索引位置的字元

System.out.println("charAt:" + s.charAt(7));

System.out.println("----------------------");

// int indexOf(int ch):返回指定字元在此字串中第一次出現處的索引。

System.out.println("indexOf:" + s.indexOf('l'));

System.out.println("----------------------");

// int indexOf(String str):返回指定字串在此字串中第一次出現處的索引。

System.out.println("indexOf:" + s.indexOf("owo"));

System.out.println("----------------------");

// int indexOf(int ch,int fromIndex):返回指定字元在此字串中從指定位置後第一次出現處的索引。

System.out.println("indexOf:" + s.indexOf('l', 4));

System.out.println("indexOf:" + s.indexOf('k', 4)); // -1

System.out.println("indexOf:" + s.indexOf('l', 40)); // -1

System.out.println("----------------------");

// 自己練習:int indexOf(String str,int

// fromIndex):返回指定字串在此字串中從指定位置後第一次出現處的索引。

// String substring(int start):從指定位置開始擷取字串,預設到末尾。包含start這個索引

System.out.println("substring:" + s.substring(5));

System.out.println("substring:" + s.substring(0));

System.out.println("----------------------");

// String substring(int start,int

// end):從指定位置開始到指定位置結束擷取字串。包括start索引但是不包end索引

System.out.println("substring:" + s.substring(3, 8));

System.out.println("substring:" + s.substring(0, s.length()));

}

}

遍歷獲取字串中的每一個字元

package cn.it18zhang_04;

/*

 * 需求:遍歷獲取字串中的每一個字元

 *

 * 分析:

 * A:如何能夠拿到每一個字元呢?

 * char charAt(int index)

 * B:我怎麼知道字元到底有多少個呢?

 * int length()

 */

public class StringTest {

public static void main(String[] args) {

// 定義字串

String s = "helloworld";

// 原始版本

// System.out.println(s.charAt(0));

// System.out.println(s.charAt(1));

// System.out.println(s.charAt(2));

// System.out.println(s.charAt(3));

// System.out.println(s.charAt(4));

// System.out.println(s.charAt(5));

// System.out.println(s.charAt(6));

// System.out.println(s.charAt(7));

// System.out.println(s.charAt(8));

// System.out.println(s.charAt(9));

// 只需要我們從0取到9

// for (int x = 0; x < 10; x++) {

// System.out.println(s.charAt(x));

// }

// 如果長度特別長,我不可能去數,所以我們要用長度功能

for (int x = 0; x < s.length(); x++) {

// char ch = s.charAt(x);

// System.out.println(ch);

// 僅僅是輸出,我就直接輸出了

System.out.println(s.charAt(x));

}

}

}

統計一個字串中大寫字母字元,小寫字母字元,數字字元出現的次數。(不考慮其他字元)

package cn.it18zhang_04;

/*

 * 需求:統計一個字串中大寫字母字元,小寫字母字元,數字字元出現的次數。(不考慮其他字元)

 * 舉例:

 * "Hello123World"

 * 結果:

 * 大寫字元:2

 * 小寫字元:8

 * 數字字元:3

 *

 * 分析:

 * 前提:字串要存在

 * A:定義三個統計變數

 * bigCount=0

 * smallCount=0

 * numberCount=0

 * B:遍歷字串,得到每一個字元。

 * length()charAt()結合

 * C:判斷該字元到底是屬於那種型別的

 * 大:bigCount++

 * 小:smallCount++

 * 數字:numberCount++

 *

 * 這道題目的難點就是如何判斷某個字元是大的,還是小的,還是數字的。

 * ASCII碼錶:

 * 048

 * A65

 * a97

 * 雖然,我們按照數字的這種比較是可以的,但是想多了,有比這還簡單的

 * char ch = s.charAt(x);

 *

 * if(ch>='0' && ch<='9') numberCount++

 * if(ch>='a' && ch<='z') smallCount++

 * if(ch>='A' && ch<='Z') bigCount++

 *D:輸出結果。

 *

 * 練習:把給定字串的方式,改進為鍵盤錄入字串的方式。

 */

public class StringTest2 {

public static void main(String[] args) {

//定義一個字串

String s = "Hello123World";

//定義三個統計變數

int bigCount = 0;

int smallCount = 0;

int numberCount = 0;

//遍歷字串,得到每一個字元。

for(int x=0; x<s.length(); x++){

char ch = s.charAt(x);

//判斷該字元到底是屬於那種型別的

if(ch>='a' && ch<='z'){

smallCount++;

}else if(ch>='A' && ch<='Z'){

bigCount++;

}else if(ch>='0' && ch<='9'){

numberCount++;

}

}

//輸出結果。

System.out.println("大寫字母"+bigCount+"");

System.out.println("小寫字母"+smallCount+"");

System.out.println("數字"+numberCount+"");

}

}

String類的轉換功能

byte[] getBytes()

char[] toCharArray()

static String valueOf(char[] chs)

static String valueOf(int i)

String toLowerCase()

String toUpperCase()

String concat(String str)

package cn.itcast_05;

/*

 * String的轉換功能:

 * byte[] getBytes():把字串轉換為位元組陣列。

 * char[] toCharArray():把字串轉換為字元陣列。

 * static String valueOf(char[] chs):把字元陣列轉成字串。

 * static String valueOf(int i):int型別的資料轉成字串。

 * 注意:String類的valueOf方法可以把任意型別的資料轉成字串。

 * String toLowerCase():把字串轉成小寫。

 * String toUpperCase():把字串轉成大寫。

 * String concat(String str):把字串拼接。

 */

public class StringDemo {

public static void main(String[] args) {

// 定義一個字串物件

String s = "JavaSE";

// byte[] getBytes():把字串轉換為位元組陣列。