1. 基本輸入輸出:
1) JDK
一般用法為:
import java.io.*
import java.util.*
public class
{
public static void main(String args[])
{
Scanner cin = new Scanner(new BufferedInputStream(System.in));
...
}
}
當然也可以直接 Scanner cin = new Scanner(System.in); 只是加Buffer可能會快一些。
2)
讀一個整數(shù): int n = cin.nextInt(); 相當于 scanf("%d", &n); 或 cin >> n;
讀一個字符串:String s = cin.next(); 相當于 scanf("%s", s); 或 cin >> s;
讀一個浮點數(shù):double t = cin.nextDouble(); 相當于 scanf("%lf", &t); 或 cin >> t;
讀一整行: String s = cin.nextLine(); 相當于 gets(s); 或 cin.getline(...);
判斷是否有下一個輸入可以用 cin.hasNext() 或 cin.hasNextInt() 或 cin.hasNextDouble() 等,具體見 TOJ 1001 例程。
3) 輸出一般可以直接用 System.out.print() 和 System.out.println(),前者不輸出換行,而后者輸出。
比如:System.out.println(n); // n 為 int 型
同一行輸出多個整數(shù)可以用
System.out.println(new Integer(n).toString() + " " + new Integer(m).toString());
也可重新定義:
static PrintWriter cout = new PrintWriter(new BufferedOutputStream(System.out));
cout.println(n);
4) 對于輸出浮點數(shù)保留幾位小數(shù)的問題,可以使用DecimalFormat類。
import java.text.*;
DecimalFormat f = new DecimalFormat("#.00#");
DecimalFormat g = new DecimalFormat("0.000");
double a = 123.45678, b = 0.12;
System.out.println(f.format(a));
System.out.println(f.format(b));
System.out.println(g.format(b));
這里0指一位數(shù)字,#指除0以外的數(shù)字。
2. 大數(shù)字
BigInteger 和 BigDecimal 是在java.math包中已有的類,前者表示整數(shù),后者表示浮點數(shù)。
用法:不能直接用符號如+、-來使用大數(shù)字,例如:
import java.math.* // 需要引入 java.math 包
BigInteger a = BigInteger.valueOf(100);
BigInteger b = BigInteger.valueOf(50);
BigInteger c = a.add(b) // c = a + b;
主要有以下方法可以使用:
BigInteger add(BigInteger other)
BigInteger subtract(BigInteger other)
BigInteger multiply(BigInteger other)
BigInteger divide(BigInteger other)
BigInteger mod(BigInteger other)
int compareTo(BigInteger other)
static BigInteger valueOf(long x)
輸出大數(shù)字時直接使用 System.out.println(a) 即可。
3. 字符串
String 類用來存儲字符串,可以用charAt方法來取出其中某一字節(jié),計數(shù)從0開始:String a = "Hello"; // a.charAt(1) = 'e'
用substring方法可得到子串,如上例
System.out.println(a.substring(0, 4)) // output "Hell"
注意第2個參數(shù)位置上的字符不包括進來。這樣做使得 s.substring(a, b) 總是有 b-a個字符。
字符串連接可以直接用 + 號,如
String a = "Hello";
String b = "world";
System.out.println(a + ", " + b + "!"); // output "Hello, world!"
如想直接將字符串中的某字節(jié)改變,可以使用另外的StringBuffer類。
4. 調(diào)用遞歸(或其他動態(tài)方法)
在主類中 main 方法必須是 public static void 的,在 main 中調(diào)用非static類時會有警告信息,可以先建立對象,然后通過對象調(diào)用方法:
public class
{
...
void dfs(int a)
{
if (...) return;
dfs(a+1);
}
public static void main(String args[])
{
...
Main e = new
e.dfs(0);
...
}
}
5. 其他注意的事項
1) Java 是面向?qū)ο蟮恼Z言,思考方法需要變換一下,里面的函數(shù)統(tǒng)稱為方法,不要搞錯。
2) Java 里的數(shù)組有些變動,多維數(shù)組的內(nèi)部其實都是指針,所以Java不支持fill多維數(shù)組。
數(shù)組定義后必須初始化,如 int[] a = new int[100];
3) 布爾類型為 boolean,只有true和false二值,在 if (...) / while (...) 等語句的條件中必須為boolean類型。
在C/C++中的 if (n % 2) ... 在Java中無法編譯通過。
4) 下面在java.util包里Arrays類的幾個方法可替代C/C++里的memset、qsort/sort 和 bsearch:
Arrays.fill();
Arrays.sort();
Arrays.binarySearch();