Flow control in Java — Scanner, if/else and switch with Laura’s grade (and the question the program skipped)
In my first lab with Scanner I wrote the simplest program in the world: ask for the credits and then the name. I ran it, typed 24, pressed Enter… and the program greeted me with a «Hello, » and nothing else. It didn’t even let me type the name. I thought the computer was slow, ran it three times and always got the same. It wasn’t the computer: it was the keyboard buffer, Scanner‘s most famous trap, and you’ll see it here with its real output.
So far, in syntax and in Java variables, the data was written inside the program and the program always did the same thing. Flow control changes both: with Scanner the data comes from the keyboard, and with if, else and switch the program decides what to do with it. If you come from Python you already know the logic; if you’ve seen C in IC2, Java’s switch will feel almost identical. What’s new is in the details: the buffer, the decimal comma, the braces and break.
All the output is real, from Java 21 on my computer, which is set to Spanish. That’s why the decimals you type and the ones printf writes use a comma (7,5), while println uses a point: it’s the locale trap we’ll see below, and on a computer set to English you’d type 7.5. Where the program asks for data, you’ll see what was typed after each prompt, as in the terminal.
Table of Contents
Importing classes in Java: the first time you see import
Scanner doesn’t come «built in» like String or System: it lives in the java.util package and you have to import it. The import goes at the top of the file, before the class:
import java.util.Scanner; // the Scanner class from the java.util package
public class MyProgram {
public static void main(String[] args) {
// Scanner can be used here
}
}
java.util is the package (something like a Python module) and Scanner is the class. You can also write import java.util.*; to bring in every class in the package, but it’s better to import only the ones you use: anyone reading the program sees at a glance what it needs. If you forget the import, javac tells you with cannot find symbol on the Scanner line. VS Code with the Java extension adds it for you, but it’s worth knowing what it does.
String, System and Math don’t need an import because they belong to the java.lang package, which Java always imports.
What Scanner is and how to create it
Scanner is the class that reads what you type: the equivalent of Python’s input(). You create an object connected to standard input (System.in, the keyboard) and keep asking it for data:
import java.util.Scanner; // Scanner lives in the java.util package
/** Reading from the keyboard with Scanner: a text, an integer and a decimal (Laura's data, made up). */
public class ReadData {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // connected to the keyboard
System.out.print("Full name: ");
String name = sc.nextLine(); // the whole line, with spaces
System.out.print("Credits: ");
int credits = sc.nextInt(); // an integer
System.out.print("Average grade: ");
double average = sc.nextDouble(); // a decimal: in Spanish, with a comma
System.out.println("Hello, " + name + ": " + credits + " credits and average " + average);
sc.close(); // we close the Scanner at the end
}
}
A run (what comes after each prompt is what was typed):
Full name: Laura Santana Ruiz Credits: 24 Average grade: 7,5 Hello, Laura Santana Ruiz: 24 credits and average 7.5
new Scanner(System.in):newcreates a new object (you’ll see it all the time in Java).System.inis the keyboard, just asSystem.outwas the screen.System.out.print(without ln) leaves the cursor on the same line, so what you type appears after the prompt.- Each type has its method:
nextLine()for text,nextInt()for integers,nextDouble()for decimals. In Pythoninput()always returned text and you converted it; in Java theScannerconverts it for you. - Look at the grade: 7,5 was typed with a comma (the computer is set to Spanish) and
printlnwrites7.5. We explain it in its own section, because it’s a trap of its own. sc.close()closes theScannerwhen you don’t need it any more.
How to close a Scanner in Java
sc.close() at the end, when you’re not going to read anything else. Two warnings: closing a Scanner on System.in also closes the keyboard for the rest of the program (a new Scanner couldn’t read any more), so create just one and close it at the end. And if you don’t close it, the program works the same; VS Code just warns you that a resource wasn’t closed (resource leak).
Why there are nextInt(), nextDouble(), nextLine()… and when to use each
| Method | Reads | Example of what you type |
|---|---|---|
nextLine() | the whole line, with spaces | Laura Santana Ruiz |
next() | one word (up to the first space) | Laura |
nextInt() | an int | 24 |
nextLong() | a long | 20260004321 |
nextDouble() | a double (with your language’s comma or point) | 7,5 or 7.5 |
nextBoolean() | true or false | false |
The difference between next() and nextLine(), with «Laura Santana» typed:
import java.util.Scanner;
/** next() reads one word; nextLine() reads whatever is left of the line. */
public class NextAndNextLine {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Name and surname: ");
String word = sc.next(); // up to the first space
String rest = sc.nextLine(); // what is left of that line (with its space in front)
System.out.println("next(): [" + word + "]");
System.out.println("nextLine(): [" + rest + "]");
sc.close();
}
}
Name and surname: Laura Santana next(): [Laura] nextLine(): [ Santana]
next() keeps the first word; the following nextLine() takes whatever was left of that line, with its space in front. For full names, always nextLine().
The buffer problem: Scanner’s most common trap
Here’s my empty greeting from the start. When you type 24 and press Enter, three characters are left in the input: 2, 4 and the Enter (\n). nextInt() takes the 24 and leaves the Enter. The next nextLine() reads up to the first Enter it finds… which is already there. It returns an empty line without waiting for you to type:
import java.util.Scanner;
/** The buffer trap: nextInt() leaves the Enter, and the nextLine() after it takes it. */
public class Buffer {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Credits: ");
int credits = sc.nextInt();
System.out.print("Name: ");
String name = sc.nextLine(); // does it wait for you to type?
System.out.println("Hello, [" + name + "]: " + credits + " credits");
sc.close();
}
}
Credits: 24 Name: Hello, []: 24 credits
Look at the last line: the program writes «Name: » and, without letting you type, moves on to the greeting with an empty name (the square brackets make it obvious). The «Laura» you were going to type never even gets read.
There are two fixes, and both are in this program:
import java.util.Scanner;
/** Two fixes: an empty nextLine() that takes the Enter away, or always read lines and convert. */
public class CleanBuffer {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Credits: ");
int credits = sc.nextInt();
sc.nextLine(); // 1) takes the Enter that nextInt() left
System.out.print("Name: ");
String name = sc.nextLine();
System.out.print("Year: ");
int year = Integer.parseInt(sc.nextLine().trim()); // 2) whole line and conversion
System.out.print("Degree: ");
String degree = sc.nextLine(); // no Enter left waiting
System.out.println(name + ", " + year + "st year of " + degree + ", " + credits + " credits");
sc.close();
}
}
Credits: 24 Name: Laura Year: 1 Degree: GCID Laura, 1st year of GCID, 24 credits
- An empty
sc.nextLine();right after thenextInt()(ornextDouble()) takes away the leftover Enter. The rule: if anextLine()comes after anextInt(), put the cleaner in between. - Always read lines and convert:
Integer.parseInt(sc.nextLine().trim()). That way no Enter is ever left hanging. Many programmers do this so they don’t have to think about the buffer (thetrim()removes spaces at the ends in case one slips in).
«the program skips a question». It doesn’t skip it: the nextLine() has taken the Enter left by the previous nextInt(). Look for a nextInt() or nextDouble() just before it.
The comma or the point in nextDouble()
Scanner reads decimals in the format of the computer’s language. On a computer set to Spanish, nextDouble() expects 7,5. If you type 7.5:
import java.util.Scanner;
/** On a computer set to Spanish, nextDouble() expects a comma. */
public class CommaPoint {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Average grade: ");
double average = sc.nextDouble();
System.out.println("Read: " + average);
sc.close();
}
}
Average grade: 7.5
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:947)
at java.base/java.util.Scanner.next(Scanner.java:1602)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2573)
at CommaPoint.main(CommaPoint.java:8)
InputMismatchException: what was typed isn’t shaped like a double… in Spanish. With 7,5, the same program:
Average grade: 7,5 Read: 7.5
On a computer set to English it’s the other way round: nextDouble() accepts 7.5 and rejects 7,5. Notice the contradiction: in the code decimals always use a point (7.5), and println writes them with a point; but Scanner and printf use the language’s separator. If you want the program to accept the point on any computer, tell the Scanner which format to use with useLocale:
import java.util.Locale;
import java.util.Scanner;
/** With useLocale(Locale.US) the Scanner reads the point, on any computer. */
public class WithLocale {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in).useLocale(Locale.US);
System.out.print("Average grade: ");
double average = sc.nextDouble();
System.out.println("Read: " + average);
System.out.print("Scholarship? (true/false): ");
boolean becada = sc.nextBoolean(); // there is also nextBoolean()
System.out.println("Scholarship: " + becada);
sc.close();
}
}
Average grade: 7.5 Read: 7.5 Scholarship? (true/false): false Scholarship: false
useLocale(Locale.US) (with its import java.util.Locale;) makes it read 7.5 on any computer. And by the way, nextBoolean() reads true or false typed as they are.
If your program is going to run on computers set to different languages (yours, the lab’s, your teacher’s), useLocale(Locale.US) saves you surprises.
if/else in Java: like Python but with braces
The logic is Python’s. The shape changes: the condition goes in brackets, each block in braces and there’s no colon.
# Python
if grade >= 9:
rating = "Excellent"
elif grade >= 7:
rating = "Very good"
else:
rating = "Fail"
elif in Java: you write else if
Java has no elif: you write else if, with a space. With Laura’s grade (Spanish universities mark from 0 to 10: 9 or more is the top band, 7 to 9 «very good» and 5 a pass):
import java.util.Scanner;
/** if / else if / else: the rating of a grade (Python's elif is else if). */
public class Rating {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Final grade: ");
double grade = sc.nextDouble();
String rating;
if (grade >= 9) {
rating = "Excellent";
} else if (grade >= 7) { // only checked if the previous one was false
rating = "Very good";
} else if (grade >= 5) {
rating = "Pass";
} else {
rating = "Fail";
}
System.out.println(grade + " → " + rating);
sc.close();
}
}
Final grade: 7,1 7.1 → Very good
And with 4,99, which is where you see whether the limits are right:
Final grade: 4,99 4.99 → Fail
In a chain of else if only one branch runs: Java tries the conditions from top to bottom and keeps the first true one. That’s why grade >= 7 doesn’t need «and less than 9»: if we get there it’s because grade >= 9 was already false. And that’s why the order matters:
/** The order of the else ifs matters: the first true condition wins. */
public class WrongOrder {
public static void main(String[] args) {
double grade = 9.5;
if (grade >= 5) {
System.out.println("Pass");
} else if (grade >= 7) {
System.out.println("Very good");
} else if (grade >= 9) {
System.out.println("Excellent");
}
}
}
Aprobado
A 9.5 comes out as «Pass»: grade >= 5 is the first true condition and the rest aren’t even checked. With ranges, from the most demanding to the least.
Comparison and logical operators
The comparison operators are Python’s: ==, !=, <, <=, >, >=. The logical ones change name:
| Python | Java | Means |
|---|---|---|
and | && | both conditions |
or | || | at least one |
not | ! | the opposite |
/** &&, || and ! with the grant conditions (made-up requirements). */
public class Logical {
public static void main(String[] args) {
int credits = 24;
double average = 7.1;
boolean repeater = false;
boolean grant = credits >= 24 && average >= 6.5; // both have to hold
boolean warning = average < 5 || repeater; // one is enough
boolean firstTime = !repeater; // negates it
System.out.println("Gets the grant? " + grant);
System.out.println("Tutor warning? " + warning);
System.out.println("First time? " + firstTime);
if (credits >= 24 && average >= 6.5) {
System.out.println("Laura can apply for the grant");
}
}
}
Gets the grant? true Tutor warning? false First time? true Laura can apply for the grant
Check: 24 >= 24 is true and 7.1 >= 6.5 too, so the grant gives true; 7.1 < 5 is false and so is repeater, so the warning gives false.
Short circuit: why the order in && matters
&& and || are lazy: if the left part already decides the result, they don’t evaluate the right. With &&, if the left is false, there’s nothing more to do. That lets you protect a dangerous operation:
/** Short circuit: if the left of && is already false, Java does not look at the right. */
public class ShortCircuit {
public static void main(String[] args) {
String username = null; // not logged in yet
if (username != null && username.equals("lsantana")) { // safe: the right is not evaluated
System.out.println("Welcome");
} else {
System.out.println("Not logged in");
}
if (username.equals("lsantana") && username != null) { // the other way round: equals on null
System.out.println("Welcome");
}
}
}
Not logged in
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "<local1>" is null
at ShortCircuit.main(ShortCircuit.java:10)
The first if works: username != null is false and Java doesn’t even try the equals. The second puts the conditions the other way round: username.equals(...) runs first on null and the program blows up with a NullPointerException. (The <local1> in the message is the variable username: javac doesn’t keep the names of local variables unless you compile with -g.)
Comparing texts in an if: equals, never ==
You saw it in the variables theory, but with Scanner it stops being a curiosity: a text read from the keyboard is always a new object.
import java.util.Scanner;
/** == with a text read from the keyboard: always false. equals() compares the letters. */
public class CompareText {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Username: ");
String username = sc.nextLine();
if (username == "lsantana") {
System.out.println("== says: it is Laura");
} else {
System.out.println("== says: not Laura");
}
if (username.equals("lsantana")) {
System.out.println("equals says: it is Laura");
}
if (username.equalsIgnoreCase("LSANTANA")) {
System.out.println("equalsIgnoreCase too");
}
sc.close();
}
}
Username: lsantana == says: not Laura equals says: it is Laura equalsIgnoreCase too
Exactly lsantana was typed and still == says no. equals() compares the letters; equalsIgnoreCase() compares them ignoring upper and lower case.
if without braces: when it’s fine and when it’s a trap
If the block has a single statement, the braces can be left out. The problem comes when you add a second line with the same indentation:
/** Without braces, the if only controls the first statement: indentation does not count. */
public class NoBraces {
public static void main(String[] args) {
double grade = 4.2;
if (grade >= 5)
System.out.println("Pass");
System.out.println("Well done, Laura"); // it is outside the if
System.out.println("End");
}
}
Well done, Laura Fin
With 4.2, «Pass» doesn’t appear (right), but «Well done, Laura» does (wrong). In Python indentation decided what was inside the if; in Java it doesn’t count: without braces, only the first statement belongs to the if. And there’s a cousin of this mistake that’s even harder to spot:
/** A ; after the if closes it: the block below always runs. */
public class Semicolon {
public static void main(String[] args) {
int credits = 12;
if (credits >= 24); {
System.out.println("Full enrolment");
}
}
}
Full enrolment
With 12 credits it says «Full enrolment». The ; after the bracket is an empty statement: the if ends there, and the block in braces below is a loose block that always runs. javac compiles it without a word.
Trusting the indentation. In FP2, always braces, even if the block has one line, and never a ; after the bracket of an if.
The ternary operator: if/else on one line
The ternary is an if/else that returns a value: condition ? value_if_true : value_if_false. It’s Python’s x if c else y in a different order:
/** The ternary operator: an if/else that returns a value. */
public class Ternary {
public static void main(String[] args) {
double average = 7.1;
int failedCount = 1;
String status = (average >= 5) ? "PASSED" : "FAILED";
String text = failedCount + (failedCount == 1 ? " subject pending" : " subjects pending");
int larger = (7 > 8) ? 7 : 8;
System.out.println("Status: " + status);
System.out.println(text);
System.out.println("The larger of 7 and 8: " + larger);
}
}
Status: PASSED 1 subject pending The larger of 7 and 8: 8
It’s great for choosing between two texts (singular or plural) or two numbers. What you shouldn’t do is nest them: n >= 9 ? "Excellent" : n >= 7 ? "Very good" : ... compiles, but it’s hard to read. For more than two cases, if/else if.
switch/case in Java: compared with C
If you’ve seen C’s switch in IC2, Java’s is almost the same: it compares a variable with specific values (case), jumps to the one that matches and default plays the role of else. The differences: Java accepts String in a switch (C doesn’t) and, since Java 14, a form with arrows and no break.
Why break is compulsory: fall-through
The switch jumps to the right case and from there keeps going down until it finds a break (or the end). If you forget the break, it also runs the cases below. That’s fall-through, just like in C:
/** Without break, the switch keeps falling through the cases (fall-through), just like in C. */
public class NoBreak {
public static void main(String[] args) {
int day = 2;
switch (day) {
case 1:
System.out.println("Monday: FP2");
case 2:
System.out.println("Tuesday: IC2");
case 3:
System.out.println("Wednesday: FP2");
break;
case 4:
System.out.println("Thursday: Algebra");
break;
}
}
}
Tuesday: IC2 Wednesday: FP2
With day = 2 it jumps to case 2: («Tuesday») and, since there’s no break, carries on into case 3: («Wednesday»); the break in case 3 takes it out. Monday doesn’t appear because a switch doesn’t start at the top: it starts at its case.
switch with String: what C can’t do
An admin office menu (made-up procedures) with two cases sharing an action, which is the good use of fall-through:
import java.util.Scanner;
/** switch with String and grouped cases: the admin office menu (made-up procedures). */
public class OfficeMenu {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Procedure (enrolment, certificate, grant, timetable): ");
String procedure = sc.nextLine().trim().toLowerCase();
switch (procedure) {
case "enrolment":
System.out.println("Window 1");
break;
case "certificate":
case "grant": // two cases, the same action
System.out.println("Window 2");
break;
default:
System.out.println("Not an admin office procedure: " + procedure);
}
sc.close();
}
}
Procedure (enrolment, certificate, grant, timetable): Grant Window 2
Procedure (enrolment, certificate, grant, timetable): timetable Not an admin office procedure: horario
Grant was typed with a capital letter: trim().toLowerCase() turns it into grant before comparing. Inside, the switch compares the Strings with equals(), so there’s no == trap here. And case "certificate": with nothing under it falls into case "grant":: both go to window 2.
switch works with int, char and String, not double
It accepts int (and char, byte, short), String and enums. It does not accept long, float, double or boolean:
public class SwitchDouble {
public static void main(String[] args) {
double grade = 7.5;
switch (grade) {
case 7.5:
System.out.println("Very good");
break;
}
}
}
SwitchDouble.java:4: error: selector type double is not allowed
switch (grade) {
^
1 error
It makes sense: comparing a double with exact values is a bad idea (7.5 could be 7.4999999…). For grade ranges, if/else if.
switch with arrows (Java 14 and later)
Java 21 (the one we use) accepts a cleaner form: case X ->, several values separated by commas and no fall-through (no break needed). Also, a switch can return a value:
/** Since Java 14: switch with arrows (no fall-through) and a switch that returns a value. */
public class SwitchArrows {
public static void main(String[] args) {
int day = 6;
switch (day) {
case 1, 3 -> System.out.println("FP2 in the morning");
case 2, 4 -> System.out.println("IC2 in the morning");
case 6, 7 -> System.out.println("Weekend");
default -> System.out.println("Friday: tutorials");
}
int year = 1;
double creditPrice = switch (year) { // switch as an expression: returns the price
case 1 -> 15.50;
case 2, 3 -> 16.20;
default -> 17.00;
};
System.out.println("Credit price in year " + year + ": " + creditPrice);
}
}
Weekend Credit price in year 1: 15.5
case 6, 7 -> groups without tricks, and the price switch works as an expression: it ends in ; and its result is stored in creditPrice (made-up prices). In the notes and in many FP2 exams you’ll see the classic form with break, so it’s worth knowing both.
If your classic switch has a break in every case, turn it into arrows: it’s shorter and you can no longer forget a break.
switch versus if/else: when to use each
| Situation | Better |
|---|---|
| One variable compared with fixed values (menu option, day, procedure) | switch |
Ranges (grade >= 7), decimals or conditions with several variables | if/else if |
| Choosing between two values in an expression | ternary |
| Several values with the same action | switch with case 6, 7 -> |
A complete program with everything together
Laura’s final FP2 grade, now read from the keyboard: Scanner, validation with ||, a chain of else if, the ternary and a switch with arrows (made-up 60/40 weights, as in the variables practice).
import java.util.Scanner;
/** All together: read with Scanner, decide with if, sum up with the ternary and answer with switch. */
public class GradeCard {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("=== FP2 final grade ===");
System.out.print("Student: ");
String name = sc.nextLine();
System.out.print("Midterm 1 (0-10): ");
double midterm1 = sc.nextDouble();
System.out.print("Midterm 2 (0-10): ");
double midterm2 = sc.nextDouble();
System.out.print("Practical (0-10): ");
double practical = sc.nextDouble();
if (midterm1 < 0 || midterm1 > 10 || midterm2 < 0 || midterm2 > 10 || practical < 0 || practical > 10) {
System.out.println("A grade is outside 0-10");
sc.close();
return; // main ends here
}
double theory = (midterm1 + midterm2) / 2; // already double: no integer division
double grade = 0.6 * theory + 0.4 * practical;
String rating;
if (grade >= 9) {
rating = "Excellent";
} else if (grade >= 7) {
rating = "Very good";
} else if (grade >= 5) {
rating = "Pass";
} else {
rating = "Fail";
}
String status = (grade >= 5) ? "PASSED" : "FAILED";
System.out.printf("%s: theory %.2f, practical %.2f → grade %.2f (%s, %s)%n",
name, theory, practical, grade, rating, status);
switch (rating) {
case "Excellent" -> System.out.println("In the running for top honours!");
case "Very good" -> System.out.println("Very good, keep it up.");
case "Pass" -> System.out.println("Passed; go for more in the next one.");
default -> System.out.println("Chin up: the resit is in July.");
}
sc.close();
}
}
With Laura’s grades:
=== FP2 final grade === Student: Laura Santana Midterm 1 (0-10): 7,5 Midterm 2 (0-10): 8 Practical (0-10): 6,5 Laura Santana: theory 7,75, practical 6,50 → grade 7,25 (Notable, PASSED) Very good, keep it up.
And with an 11 typed by mistake:
=== FP2 final grade === Student: Pablo Medina Midterm 1 (0-10): 7,5 Midterm 2 (0-10): 11 Practical (0-10): 6 A grade is outside 0-10
Checking by hand: theory (7.5 + 8) / 2 = 7.75; grade 0.6 × 7.75 + 0.4 × 6.5 = 4.65 + 2.6 = 7.25 → Very good. As midterm1 and midterm2 are already double, dividing by 2 truncates nothing (the variables trap only bites with two ints). And the return inside the first if ends main right there: with an 11, the rest doesn’t run.
Common flow control mistakes
- The skipped question:
nextLine()afternextInt()with no cleaner. InputMismatchException: the decimal typed doesn’t match the computer’s language (7.5 on a Spanish one, 7,5 on an English one); or useuseLocale(Locale.US).==with texts: alwaysequals().else ifin the wrong order: with ranges, from the most demanding condition to the least.- if without braces or with
;: indentation doesn’t count; always braces. - Forgotten
break: theswitchkeeps falling. Or switch to arrows. switchon adouble: doesn’t compile; for ranges,if.
Watch it step by step in Python Tutor
pythontutor.com runs the code line by line and marks which line runs at each step: perfect for seeing which branches are skipped. Choose Java and paste this program (no Scanner: Python Tutor doesn’t let you type, so the data is fixed):
public class FlowTutor {
public static void main(String[] args) {
double midterm1 = 7.5;
double midterm2 = 8.0;
double practical = 6.5;
double grade = 0.6 * (midterm1 + midterm2) / 2 + 0.4 * practical;
String rating;
if (grade >= 9) {
rating = "Excellent";
} else if (grade >= 7) {
rating = "Very good";
} else {
rating = grade >= 5 ? "Pass" : "Fail";
}
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
case 2:
System.out.println("Tuesday");
case 3:
System.out.println("Wednesday");
}
System.out.println(grade + " " + rating);
}
}
Output:
Tuesday Wednesday 7.25 Notable
What to watch step by step:
- In the
ifchain, the «current line» arrow goes throughgrade >= 9, jumps tograde >= 7and goes in: theelseand its ternary are never touched. - Look at the value of
gradein the panel:7.25, the same sum as in the complete program. - In the
switch, execution jumps straight tocase 2:(it doesn’t go throughcase 1:) and then falls intocase 3:because there’s nobreak. - At the end, the output has «Tuesday» and «Wednesday» before the grade: fall-through live.
Quick summary
| I want… | I write |
|---|---|
| Read a line | String s = sc.nextLine(); |
| Read a number | int n = sc.nextInt(); / double d = sc.nextDouble(); |
| Avoid the buffer | sc.nextLine(); after nextInt(), or Integer.parseInt(sc.nextLine().trim()) |
| Read decimals with a point on any computer | new Scanner(System.in).useLocale(Locale.US) |
| Several conditions | if (…) { } else if (…) { } else { } |
| And / or / not | && / || / ! |
| Choose between two values | cond ? a : b |
| A menu | switch (op) { case 1 -> …; default -> …; } |
| Compare texts | a.equals(b) |
Three ideas to keep:
- Scanner reads types, but leaves the Enter: after
nextInt()ornextDouble(), an emptynextLine()before reading text. - In an else if chain the first true condition wins, and braces (not indentation) say what’s inside.
switchfalls until thebreak: either abreakin everycaseor arrows.
Now it’s time to practice all this with complete programs in the Java flow control practice. And then come Java loops: with a while, the admin office menu will be able to repeat until you choose to leave.
Did this article help you? Here is how you can support SergioLearns →




IC2 practical mock exam — flowcharts, fork and threads in C (and the screenshots you can’t leave out)