MathクラスAdvertisement説明
Mathは数学系(?)ライブラリ。
Mathクラスの変数とメソッドは全部staticだから、インスタンス化しないで使うことができる。Mathクラスのオブジェクトは生成することができない。 メソッド
よく使うメソッド。
使用例 abs()
public class absTest{
public static void main(String args[]){
int a = -5;
Math.abs(a); //ここポイント
System.out.println(a);
System.out.println(Math.abs(a));
}
}
結果。
-5 5/div> 使用例 random()
ランダム。
public class rndTest{
public static void main(String args[]){
for(int i = 0; i < 10; i++){
System.out.println(Math.random());
}
}
}
結果。ランダムだから結果は毎回違う。
0.10267826179026052 0.39827774730769516 0.3961781821498739 0.5287863663803894 0.6367000478401743 0.4816806090477085 0.21569456694136113 0.8443770258653385 0.11214876932345108 0.9392102197235115よくあるのは「整数がほしい」とか。
public class rndTest{
public static void main(String args[]){
for(int i = 0; i < 10; i++){
System.out.println((int)(Math.random() * 10));
}
}
}
結果。実行ごとに違う。
5 5 1 2 4 3 3 0 9 2整数で0から9のどれかを得ることができる。 さらに応用。1〜7の整数。
public class rndTest{
public static void main(String args[]){
for(int i = 0; i < 10; i++){
System.out.println((int)(Math.random() * 7) + 1);
}
}
}
7かけてるから、0以上7未満の数字になる。そこに1を足す。7 2 6 1 1 2 6 6 3 2いろいろ応用聞くから便利。 Advertisement |
ショートカット・634・このカテゴリのトップページに戻る ・634labs UIコレクションギャラリー サイト検索Y!ログール |