Skip to content

Instantly share code, notes, and snippets.

@amippy
Last active March 20, 2016 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amippy/394a8c0eda412328f214 to your computer and use it in GitHub Desktop.
Save amippy/394a8c0eda412328f214 to your computer and use it in GitHub Desktop.
筋トレ大好きな文系女学生のJava入門〜式と演算子〜 ref: http://qiita.com/amippy/items/28130139a60e66ebb7a7
【代表的な算術演算子】
+  足し算     2 + 8 =10
-  引き算     10 - 2 = 8
*  掛け算     2 x 5 = 10
/  割り算     3.2 / 2 →1.6 9/2 → 4
%  割り算のあまり 9 % 2 → 1
【代入演算子】:右から左に代入する演算子
=   右辺を左辺に代入  a = 10 → a
+=  左辺と右辺を足してから左辺に代入
-=  左辺から右辺を引き算し、左辺に代入
*=  左辺と右辺を掛け算し、左に代入
/=  左辺と右辺を割り算し、左に代入
%=  左辺と右辺を割り算し、そのあまりを左に代入
+=  左辺後ろに右を連結して代入  a += "腹筋" → a //(a =a+ "腹筋")と同じ
1 public class Muscle{
2 public static void main(String[] args){
3 String muscle = "15";
4 int a = Integer.parseInt(muscle);
5 System.out.println("腹筋の回数は"+(muscle+100)+"回ですよ❤︎!!");
6 }
7 }
【乱数を発生させる】
int a = new java.util.Random().nextInt(1);
・1は発生させる乱数の値
・1に1以上の整数を指定してこの命令を呼び出すと、0以上かつ1で指定した数字未満のランダムな整数がaに代入される
1に100を代入すると、aには0〜99のいずれかが代入される
1 public class Muscle{
2 public static void main(String[] args){
3 int a = new java.util.Random().nextInt(100);
4 System.out.println("今日の腕立ての回数は"+a+"です!!");
5 }
6 }
【キーボードから1行の文字列の入力を受け付ける命令】
String input = new java.util.Scanner(System.in).nextLine();
【キーボードから1つの整数の入力を受け付ける命令】
int input = new java.util.Scanner(System.in).nextIn();
・これらの文を実行すると、プログラムは一時停止となり、ユーザーがキーボードから文字入力できる
・入力後、入力内容が変数inputに代入される
・nextLine()は文字列を受け取る    
・nextInt()は数字の入力を受け取る
1 public class Muscle{
2 public static void main(String[] args){
3 System.out.println("名前を入力してください!");
4 String name = new java.util.Scanner(System.in).nextLine();
5 System.out.println("年齢を入力してください!!");
6 int age = new java.util.Scanner(System.in).nextInt();
7 System.outprintln("Welcome!"+age+"歳の"+name+"さん!");
8 }
9 }
【インクリメントとデクリメント演算子】:変数の内容を1だけ増やしたり減らしたりする場合
++ 値を1増やす
-- 値を1減らす
1 public class MuscleWorld{
2 public static void main(String[] args){
3 int a = 10;
4 a++; /*aの内容が1増える*/
5 System.out.println(a);
6 }
7 }
【命令実行の文】
呼び出す命令の名前(引数);
【改行せずに画面に文字を入力する】
System.out.print(1);
/*画面に1を表示するが、改行せずに画面に表示されます*/
1 public class Muscle{
2 public static void main(String[] args){
3 String niku = "腹斜筋";
4 System.out.print("私のチャームポイントは");
5 System.out.print(niku);
6 System.out.print("です!");
7 }
8 }
【2つの値を比較して大きいほうの数字を代入する命令】
int p( = Math.max(1,2);
/*1or2は比較したい値や式。大きいほうの値がpに代入される。変数pはp以外でもOK*/
1 public class Muscle{
2 public static void main(String[] args){
3 int a = 10;
4 int b = 5;
5 int p = Math.max(a,b);
6 System.out.println("比較:"+a+"と"+b+"とで大きいほうは"+p);
7 }
8 }
【文字列を数字に変換する命令】
int a = Integer.parseInt(1);
/*1は数字として解釈させたい文字列("10")など*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment