1.用戶交互scanner
- Next()
public class demo1 {
public static void main(String[] args) {
//創建一個scanner對象
Scanner scanner = new Scanner(System.in);
System.out.println("請使用next方式進行接收:");
//判斷有無輸入字符
if(scanner.hasNext()){
String str=scanner.next();
System.out.println("輸入的內容是"+str);
}
//關閉scanner,否則一只占用資源
scanner.close();
}
}
/*輸出結果是:
請使用next方式進行接收:
happy newyear
輸入的內容是happy
*/
-
Nextline()
public class demo2 { public static void main(String[] args) { //創建一個scanner對象 Scanner scanner = new Scanner(System.in); System.out.println("請使用nextline方式進行接收:"); //判斷有無輸入字符 if(scanner.hasNextLine()){ String str=scanner.nextLine(); System.out.println("輸入的內容是"+str); } //關閉scanner,否則一只占用資源 scanner.close(); } } /* 請使用nextline方式進行接收: happy newyear 輸入的內容是happy newyear */
-
一定注意close掉對象,否則一直占用
2.scanner進階使用
-
在while中使用scanner
public class demo2 { public static void main(String[] args) { //創建一個scanner對象 Scanner scanner = new Scanner(System.in); //判斷有無輸入字符 double sum=0; int m=0; while(scanner.hasNextDouble()) { double x=scanner.nextDouble(); sum+=x; m++; } System.out.println(""+sum); System.out.println(""+m); //關閉scanner,否則一只占用資源 scanner.close(); } }
***跳過順序結構,if,switch,while,dowhile,for, break,coutinue,goto
3.for循環
-
System.out.println();
-
System.out.print();
-
打印99乘法表
for(int i=1;i<10;i++) { for(int j=1;j<=i;j++) { System.out.print(""+i+"*"+j+"="+(i*j)+"\t"); } System.out.println(); }
-
快捷方式:5.for
4.增強for
-
用於遍歷數組
int[] numbers={1,2,3}; for(int x:numbers){ System.out.print(x+"\t"); }
-
debug
5.方法
-
方法名
· 函數名用首字母大寫的英文單詞組合表示(如用動詞+名詞的方法),其中至少有一個動詞
· 應該避免的命名方式
§ 和繼承來的函數名一樣。即使函數的參數不一樣,也盡量不要這么做,除非想要重載它
§ 只由一個動詞組成,如:Save、Update。改成如:SaveValue、UpdateDataSet則比較好
· 函數參數的命名規則
§ 函數參數應該具有自我描述性,應該能夠做到見其名而知其意
§ 用匈牙利命名法命名
-
public static void main(String[] args) { int sum=add(1,2); System.out.println(sum); } public static int add(int a,int b) { return a+b; }
6.方法的重載
- 要求
7.命令行傳參
-
先用javac進行編譯
-
再回到代碼的包的上層,開始執行
-
public static void main(String[] args) { for (int i = 0; i < args.length; i++) { System.out.println("args["+i+"]"+args[i]); } }
4.
8.可變參數
-
多個同類型的參數,數量可以不確定
-
只能有一個,且放在參數的最后
-
public class demo2 { public static void main(String[] args) { demo2 demo=new demo2(); demo2.test(1,2,34); } public static void test(double d,int ... x) { System.out.println(x[1]); } }
遞歸調用,沒看
9.數組
-
申明數組
int[] nums1;//首選
int nums2[];
-
創建數組
dataType[] arrayRefVar =new dataType[arraySize];
nums1=new int[10];
-
給數組賦值
-
獲取數組長度
nums1.length
-
聲明數組
放在棧中,並不實際存在
-
創建數組
放在堆中
-
靜態初始化
int[] a={1,2,3,4,5};
-
動態初始化
int[] b; b[0]=1; ...
11.arrays類詳細
- 在idea中輸入Arrays
- 選擇goto,選擇deceleration and usages,選擇左下角structure,可以查看arrays類的方法目錄
- Arrays.sort()等