標籤:lin ase nbsp tin int 掃描 退出 switch ++
1、輸入以及輸出
當通過new Scanner(System.in)建立一個Scanner,控制台會一直等待輸入,直到敲斷行符號鍵結束,把所輸入的內容傳給Scanner,作為掃描對象。如果要擷取輸入的內容,則只需要調用Scanner的nextLine()方法即可。代碼如下:
Scanner input = new Scanner(System.in);
System.out.println("提示:輸入");
int a = input.nextInt();
2、基本語句
if語句:if(布林運算式){
//如果布林運算式為ture,就執行的語句
}
例子:
Scanner input = new Scanner(System.in);
System.out.println("輸入一個數");
int a = input.nextInt();
if (a > 10) {
System.out.println(a);
}
if else語句:if(布林運算式){
//當布林運算式為ture時執行
}else{
//當布林運算式偉false時執行
}
例子:
Scanner input = new Scanner(System.in);
System.out.println("輸入一個數");
int a = input.nextInt();
if (a > 10) {
System.out.println(a);
}else{
System.out.println(a);
}
switch語句:
switch (變數) {
case 值:
break;
case 值:
break;
default:
break;
}
for迴圈://已知迴圈次數
for(初始化;布林運算式;更新){
//語句
}
例子:9*9法則
for (int a = 1; a <= 9; a++) {
for (int b = 1; b <= a; b++) {
int c = a * b;
System.out.print(b+ "*" + a+ "=" + c+" ");
}
System.out.println();
}
while迴圈://未知迴圈次數
while(布林運算式){
//語句
}
例子:
int a=1;
while(a<=10){
System.out.print(a+" ");
a++;
}
break語句://終止當前迴圈
例子:
int k=1;
while(k<=10){
System.out.print(k+" ");
if(k==6){
break;
}
k++;
}
continue語句://退出當前迴圈,但是不影響後邊的迴圈
例子:
System.out.print("for迴圈");
System.out.println();
for (int i = 10; i > 0; i--) {
if (i % 2 == 0) {
continue;
}System.out.print(i+" ");
}
JAVA 入門編程