Assignment and Input
| English | Chinese | Pinyin |
|---|---|---|
| assignment statement | 赋值语句 | fù zhí yǔ jù |
The assignment statement
- An assignment statement 赋值语句 puts a value into a variable:
x = 5; - The single
=means "store into," not "is equal to." - Java evaluates the right side first, then stores the result in the left-side variable.
count = count + 1;reads the oldcount, adds1, and stores it back.
Right-to-left flow
- Think of
=as a left-pointing arrow:total ← price * qty. - The variable on the left must already be declared (with a type).
- A later assignment overwrites the old value — the box holds only the newest.
- You can declare and assign in one line:
int x = 5;
Reading input with Scanner
- To read user input, Java uses a
Scannerobject tied toSystem.in. Scanner sc = new Scanner(System.in);creates it.sc.nextInt()reads anint;sc.nextDouble()adouble;sc.next()one word.- Store what you read in a variable:
int age = sc.nextInt();
Match the read to the type
- Use the reading method that matches the type you expect.
nextInt()for whole numbers,nextDouble()for decimals,nextLine()for a whole line.- A mismatch (e.g.
nextInt()on the text "hello") causes a run-time error. - Read into a correctly-typed variable so the rest of the code works.
= is assignment, not equality — and it flows right-to-left. x = x + 1 is not a contradiction; it computes x + 1 and stores it back in x. (Testing equality later uses ==, a different operator.) With Scanner, match the method to the type: nextInt() reads an integer, and reading a non-number throws a run-time error.
Reading and updating a score:
int score = sc.nextInt();→scoregets whatever number the user typed.score = score + 10;→ right sidescore + 10is computed, then stored back.- If the user typed
40,scoreis now50.
An assignment statement x = value; evaluates the right side first, then stores it in the left variable (= is "store into," not equality). Read input with a Scanner: nextInt(), nextDouble(), or next()/nextLine() — match the method to the type you expect.
Right side first, then store
Each assignment evaluates the right side, then overwrites the box.
In Java, the single = sign means...
= is assignment; == tests equality.
score is 40, then score = score + 10; runs. What is score now?
Right side 40+10 = 50 is stored back into score.
Which Scanner method reads a whole number?
nextInt() reads an int; nextDouble() reads a decimal.
Java evaluates the right side of an assignment before storing into the left variable.
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.
The method expects an int; text mismatches it.