Java輸入函數

定義輸入函數

Scanner sc = new Scanner(System.in);

[建議]只使用sc.nextLine()

使用sc.nextLine()讀取輸入的一行字符串,然後操作字符串,使其符合我們的預期類型。
sc.nextLine()函數以enter鍵爲結束標誌,並且會處理enter鍵。

1.字符串的分割

String[] name=sc.nextLine().split(" ");

2.String類型轉換成基本數據類型

String str="6";
byte by = Byte.valueOf(str);
System.out.println(by);
short sh = Short.valueOf(str);
System.out.println(sh);
int in = Integer.valueOf(str);
System.out.println(in);
long lo = Long.valueOf(str);
System.out.println(lo);
float fl = Float.valueOf(str);
System.out.println(fl);
double d = Double.valueOf(str);
System.out.println(d);

3.基本數據類型轉換成String類型

System.out.println(String.valueOf('A'));

不使用任何sc.nextLine()

可以使用sc.next()讀取輸入的一個字符串,然後操作字符串,使其符合我們的預期類型。
可以使用sc.nextInt()讀取輸入的一個int類型數。
可以使用sc.nextFloat()讀取輸入的一個float類型數。
等等類似的函數。
sc.next()此類函數以空格鍵、table鍵、enter鍵爲結束標誌,並且不處理結束鍵。再次調用sc.next()此類函數,會自動忽略上次函數留下的結束鍵。但是sc.nextLine()不會忽略結束鍵,所以如果在sc.nextLine()之前調用過sc.next()此類函數,應該加入一個無效的sc.nextLine()作緩衝,抵消之前函數遺留的enter鍵。

1.舉例

String name = sc.next();
int age = sc.nextInt();
float salary = sc.nextFloat();

[慎用]混合使用sc.nextLine()和sc.next()

由於sc.nextLine()和sc.next()處理結束鍵的方式不一樣,所以要避免混合使用。
如果在sc.nextLine()之前調用過sc.next()此類函數,應該加入一個無效的sc.nextLine()作緩衝,抵消之前函數遺留的enter鍵。
1.舉例

System.out.println("請輸入你的年齡:");
int age = sc.nextInt();

// 在next(),nextInt()等函數後,加入一個無效的nextLine()以消除之前未處理的enter鍵
sc.nextLine();
System.out.println("請輸入你的姓名:");
String name = sc.nextLine();

System.out.println("請輸入你的工資:");
float salary = sc.nextFloat();

System.out.println("你的信息如下:");
System.out.println("姓名:" + name + "\n" + "年齡:" + age + "\n" + "工資:" + salary);

在線編程注意事項(需要完整寫出一個類)

1.注意輸入函數的使用
2.注意輸出函數的使用
3.調用非靜態方法之前需要創建一個類對象
示例:
牛客網編程題:迷路的牛牛

import java.util.*;

public class Main {
	public String solutionLoss(int len, String str) {
		Map<String, String> map = new HashMap<>();
		map.put("NR", "E");
		map.put("NL", "W");
		map.put("WR", "N");
		map.put("WL", "S");
		map.put("SR", "W");
		map.put("SL", "E");
		map.put("ER", "S");
		map.put("EL", "N");
		String re = "N";
		for (int i = 0; i < len; i++) {
			String tmp=re + str.substring(i, i + 1);
			re = map.get(tmp);
		}
		return re;
	}
    
    // !!!別忘記寫傳遞參數String[] args
	public static void main(String[] args) {
	    //定義輸入函數
		Scanner sc = new Scanner(System.in);
		int num = Integer.valueOf(sc.nextLine());
		String str = sc.nextLine();
		//定義一個類對象,方便調用我們寫的方法
		Main m = new Main();
		//定義輸出函數
		System.out.println(m.solutionLoss(num, str));
	}

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章