[an error occurred while processing this directive]
[an error occurred while processing this directive]
String[] A = "a:b,c".split("[:,]");
for (String a : A) {
System.out.println(a);
}
int[] ia = {1, 2, 3};
String[] sa = {"nana", "rara", "momo"};
String str = "123"; int n = Integer.parseInt(str);parseIntは引数を指定することで、16進数なども変換できる。
String str = "ff"; int n = Integer.parseInt(str, 16);あるいは、一度Integerを作ってからintを得る。
int n = (Integer.valueOf(str)).intValue(); double d = (Double.valueOf(str)).doubleValue();
String str = "true"; boolean b = "true".equalsIgnoreCase(str);"true".equals...と書くのは、もしstrがnullだったときにnullPointerExceptionを防ぐため。
DecimalFormat myFormat = new DecimalFormat("##%");
System.out.println(myFormat.format(d));
str = "123, 456";
int sp = str.indexOf('\t');
int x = Integer.parseInt(str.substring(0, sp));
int y = Integer.parseInt(str.substring(sp+1));
URL url = new URL("http://www.sodan.ecc.u-tokyo.ac.jp/");
URLConnection urlc = url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
str = br.readLine();
タイムアウトも設定できる。
urlc.setConnectTimeout(3000); // 接続のタイムアウトを 3000ミリ秒に設定 urlc.setReadTimeout(3000); // 読み込みのタイムアウトを 3000ミリ秒に設定
try{
...
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
とか。(sleep()とかでもExceptionが飛んでくるのは、へなちょこプログラマには正直迷惑なんですが…)
class Position {
int x, y;
public Position(int _x, int _y) { x = _x; y = _y; }
public boolean equals(Object o){
Position p = (Position)o;
return x == p.x && y == p.y;
}
public int hashCode()
{ return (new Integer(x+y)).hashCode(); }
}
ハッシュは色んなデータを整数にしちゃう関数。これを自分で指定するんだけど、そんな関数自分で作るのは面倒だから、既存のIntegerとかStringとかのhashCodeを使っちゃいましょう。実はx+yを指定するのは全然賢くない気もするが、めんどいから採用。こうすると、
Map m = new hashMap(); m.put(new Position(2,3), "Hello");みたいに使える。
import java.util.regex.*;
public class HelloRegex {
public static void main(String[] args){
String ptn = "^(.+\\.(jpg|JPG|jpeg|gif|GIF|png|PNG))>.*";
Pattern pattern = Pattern.compile(ptn);
String tt = "<hoe>00.jpg<ee><hoe>00.jpg<ee><hoe>00.jpg<ee><hoe>00.jpg<ee>";
String[] targets = tt.split(">");
for(int i = 0; i < targets.length; i++){
Matcher m = pattern.matcher(targets[i]);
if(m.matches()){
String ret = m.group(1);
System.out.println(ret);
}
}
}
}