Assignment and Input
導入済み
15:00
物体と手法の使用
这里是两个Java程序。第一个缺少分号。第二个将七除以二,并将结果存储为整数。编译器会停止…
英語のナレーション・英語と中国語の字幕を切り替え可能
このレッスンの内容
| English | 意味 |
|---|---|
| assignment statement/əˈsaɪnmənt ˈsteɪtmənt/ | 代入文 |
| variable/ˈveərɪəbl/ | A quantity or named value that can change or take different values. |
| object/ˈɒbdʒekt/ | An entity in a program with associated state and behaviour, often an instance of a class. |
| run-time error/rʌn taɪm ˈerə/ | A problem that occurs while a program executes and prevents an operation from completing normally. |
代入文
- 代入文は値を変数に格納します:
x = 5; - 単一の
=は「等しい」ではなく「格納する」を意味します。 - Javaはまず右辺を評価し、その結果を左辺の変数に格納します。
count = count + 1;は古いcountを読み取り、1を加えて再格納します。
右から左への流れ
=を左向きの矢印だと考えると良いです:total ← price * qty。- 左側の変数は既に宣言 (型付き) されている必要があります。
- 後続の代入は古い値を上書きします。箱には最新のものしか入りません。
- 宣言と代入を1行で行うことができます:
int x = 5;

代入操作は変数の箱に値をコピーします;その後の一方の変数に対する変更は他方の変数に影響しません

Scannerによる入力読み取り
- ユーザー入力を読む際、Javaでは**
Scanner**オブジェクトをSystem.inに紐づけて使用する。 Scanner sc = new Scanner(System.in);がそれを作成します。sc.nextInt()はintを読み取ります;sc.nextDouble()はdoubleを読み取ります;sc.next()は1つの単語を読み取ります。- 読み取った値を変数に格納します:
int age = sc.nextInt();
読み取り方法と型の一致
- 期待する型に対応する読み取りメソッドを使用します。
- 整数用
nextInt()、小数用nextDouble()、全行用nextLine()。 - 不一致 (例: 文字列 "hello" に対して
nextInt()を使用) はランタイムエラーを引き起こします。 - 正しい型の変数に読み取ると、以降のコードが正常に動作します。
= は代入であり、等価ではありません。そして右から左へ流れます。 x = x + 1 は矛盾ではありません。x + 1 を計算して x に再格納するだけです。(後に等価性をテストするには == という別の演算子を使用します。) Scanner を使う際は型に合わせてメソッドを選択します: nextInt() は整数を読み取り、非数字の読み取りはランタイムエラーを発生させます。
スコアの読み取りと更新:
int score = sc.nextInt();→scoreはユーザーが入力した数値を受け取ります。score = score + 10;→ 右辺score + 10が計算され、その後再格納されます。- ユーザーが
40を入力した場合、scoreは今や50です。
代入文 x = value; はまず右辺を評価し、左辺の変数に格納します (= は「等しい」ではなく「格納する」です)。 入力は Scanner を使用して読み取ります: nextInt(), nextDouble(), または next()/nextLine() — 期待する型に合わせてメソッドを選択します。
Right side first, then store
Each assignment evaluates the right side, then overwrites the box.
In Java, the single = sign means...
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
= is assignment; == tests equality.
score is 40, then score = score + 10; runs. What is score now?
難易度 2/5 · 140 コイン + 今日初回達成時の小ボーナス
Right side 40+10 = 50 is stored back into score.
Which Scanner method reads a whole number?
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
nextInt() reads an int; nextDouble() reads a decimal.
Java evaluates the right side of an assignment before storing into the left variable.
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
Right side first, then store — that's how x = x + 1 works.
Calling nextInt() when the user types the word 'hello' causes a run-time error.
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
The method expects an int; text mismatches it.
何が問題でしたか?この内容はサイトの運営チームだけが確認します。