Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to read an integer from the user using Scanner.
Java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int number = scanner.[1](); System.out.println("You entered: " + number); } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using nextLine() which reads a whole line as a string.
Using nextDouble() which reads a decimal number.
✗ Incorrect
The nextInt() method reads an integer value from the user input.
2fill in blank
mediumComplete the code to create a Scanner object to read input from the keyboard.
Java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner [1] = new Scanner(System.in); } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name that conflicts with class names.
Using reserved keywords as variable names.
✗ Incorrect
Variable names can be anything, but scanner is a common and clear choice.
3fill in blank
hardFix the error in the code to correctly read an integer from the user.
Java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int number = scanner.[1](); System.out.println("Number: " + number); } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using nextLine() and trying to assign to int causes errors.
Using nextDouble() when expecting an integer.
✗ Incorrect
The method nextInt() reads an integer. Using nextLine() or others causes errors or wrong types.
4fill in blank
hardFill both blanks to read an integer and print it with a message.
Java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner [1] = new Scanner(System.in); int num = [2].nextInt(); System.out.println("You typed: " + num); } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently.
Forgetting to create the Scanner object.
✗ Incorrect
Using the same variable name scanner to create and then call nextInt() is correct.
5fill in blank
hardFill all three blanks to read two integers and print their sum.
Java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner [1] = new Scanner(System.in); int a = [2].nextInt(); int b = [3].nextInt(); System.out.println("Sum: " + (a + b)); } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names for reading inputs.
Not creating the Scanner object before reading.
✗ Incorrect
Use the same Scanner variable scanner to read both integers.