java條件語言和迴圈
阿新 • • 發佈:2022-03-04
java 流程結構
public class Demo1 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("使用next方式接收"); if (scanner.hasNext()){ String str=scanner.next(); System.out.println("輸入內容為"+str); } } }
在這裡通過Scanner類來獲取使用者輸入的值,並把值給scanner,再通過判斷scanner。hasnext來有沒有輸入字串,如果輸入了字串就用scanner。next獲取賦值給str,再輸出str。
hasnextline同理
Scanner scanner = new Scanner(System.in); System.out.println("sada"); if (scanner.hasNextLine()){ String str=scanner.nextLine(); System.out.println("輸出的內容為"+str); } scanner.close();
Scanner scanner = new Scanner(System.in); //和 double sum=0; //輸入多少個數 int m=0; while (scanner.hasNextDouble()){ double x = scanner.nextDouble(); m=m+1; sum=sum+x; } System.out.println(sum); System.out.println(sum/m); scanner.close();
通過Scanner類來獲取資料給scanner物件,sum為和,m為個數,判斷scanner.nextDouble()輸入資料是否為數字如果是則通過scanner.nextDouble()輸入資料給x,並進行m=m+1;sum=sum+x;的操作,如果不是資料則輸出sum和sum/m.
String s = scanner.nextLine();
if (s.equals("hello"))
s.equals是對輸入的資料x與hello進行匹配,如果條件符合執行。
// char grade='c';
// switch (grade){
// case 'a':
// System.out.println("優秀");
// break;
// case 'b':
// System.out.println("良好");
// break;
// case 'c':
// System.out.println("及格");
// break;
// default:
// System.out.println("未知等級");
// }
switch是選擇結構,8種資料型別加str都能用,定義一個變數,然後switch對變數進行判斷,當條件符合執行對應的case,對了,要用break進行中斷。
int a=0;
while (a<0){
System.out.println(a);
}
System.out.println("----------------");
do{
a++;
System.out.println(a);
}while (a<0);
如果是dowhile是先執行完do裡的內容再判斷,而while是先判斷內容再進行執行。
if(判斷式){
執行體
}
----------------------------------
if(判斷式){
執行體
}else if(判斷式){
執行體
}else{
上述條件都不滿足時執行
}
------------------------------
switch(變數){
case value:
執行體;
break;
case value:
執行體;
break;
deault:
執行體;
break;
}
---------------------------------
do{
執行體
}while(條件判斷)
----------------------------
while(條件判斷){
執行體
}
for(初始值;條件判斷;自增減){
執行體
}
//九九乘法表
for (int i = 1; i <=9; i++) {
for (int j=1;j<=i;j++){
System.out.print(i+"*"+j+"="+(i*j)+"\t");
}
System.out.println();
}
裡面是兩個for迴圈,第一個for是控制有幾行,第二個是控制有幾列。通過i<=j來控制i有幾行j就有幾列。 System.out.print(i+""+j+"="+(ij)+"\t");
輸出j*i的結果,通過print不換行和\t有空格,跳出j迴圈輸出換行符號。
break是結束整個迴圈,而continue是結束當前迴圈去執行下次迴圈。
//列印三角形
for (int i = 1; i <= 5; i++) {
for (int j = 5; j >=i; j--) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
for (int j = 1; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
利用多重for迴圈:第一次i=1,當進行迴圈時有4個” “和一個*
。當第二次時有j<=i有兩個**,j<i只有一個*.以此類推。