Java常用基礎格式、法則
(編譯器:eclipse)
package 你好世界; //包名:你好世界
import java.util.Scanner; //輸入必備
public class first { //類名:first
public static void main(String[] args){
Scanner in=new Scanner(System.in); //輸入必備
int a;
boolean flag=true; //布爾邏輯型別,只回傳true或false
float b;
final int c; //定義常量
char sign='a'; //定義字符型變數,Java用Unicode編碼表表示字符
String s1 = new String("Hello"); //定義字串
int number=(int)(Math.random()*100+1); //定義亂數,范圍1~100的整數(強制轉換),數學函式 Math.函式型別(Math.sqrt()等
System.out.println("input a,b");
a=in.nextInt(); //讀入整數
b=in.nextFloat(); //讀入浮點型,可以此類推其他資料型別
System.out.printf(".2f",b); //輸出時保留兩位
System.out.println(a+"+"+b+"="+(a+b)); //即a+b=(a+b)【 + 表示連接】, 結果原封不動輸出,不改變精確數值
System.out.println(a+"-"+b+"="+(a-b));
System.out.println(a+"*"+b+"="+(int)(a*b)); //強制型別轉換
System.out.println(a+"/"+b+"="+(a/b)); //加減乘除四則運算輸出
System.out.println(a<=b); //關系比較,為“真”時回傳true,為“假”時回傳flase
int []numbers = new int [100]; //定義陣列--整型陣列,長度100(存放100個值) 型別[]名稱=new 型別[長度];// for(int i=0;i<numbers.length;i++) //遍歷陣列必用的回圈公式
int[][]board = new int[3][5]; //定義二維陣列,3行5列 (遍歷二維陣列用雙層回圈,外層行,內層列
for (int i=0;i<board.length;i++) { //遍歷輸入二維陣列
for(int j=0;j<board[i].length;j++) { //第i行的列的長度
board[i][j]=in.nextInt(); //陣列的輸入需要回圈
}
}
String s2;
s2=in.nextLine(); //定義字串,字串輸入控制,
s1.equals(s2) //比較兩個字串的/*內容*/是否相等,輸出true或flase
s1.compareTo(s2) //比較兩個字串的大小,輸出正數:s1>s2;負數:s1<s2; 0:s1==s2
s1.length() //表示字串s1的長度,輸出時輸出整型數字
s1.charAt(index) //用于訪問字串中第0~index的單個字符
s1.substring(x,y) //取字串中的某一部分,從第x位到第y位
s1.substring(x) //取字串的第x位到最后一位
switch(s1){ case"this":....break;...} //switch陳述句中可以使用字串
}
public static int result(int a,int b){... return ××} //定義子函式,呼叫函式(注意引數的數量和順序
// 函式頭 回傳型別 函式名 (引數表){ 函式體 }
}
- 選擇:if else
- 回圈:for , while , do-while
switch case,break,continue
–An easy program of input and output
package helloworld;
import java.util.Scanner;
public class first {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int a = in.nextInt();
System.out.println(a);
}//輸入a,輸出a
}
Look here!
I wrote it casually. Please forgive me for any offense. Best wishes to you!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/257445.html
標籤:java
上一篇:執行緒捕捉例外
