Challenge - 5 Problems
Java Input Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Java code reading an integer?
Consider the following Java program that reads an integer from the user and prints it doubled. What will be printed if the user inputs 7?
Java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int num = scanner.nextInt(); System.out.println(num * 2); } }
Attempts:
2 left
💡 Hint
Remember that nextInt() reads an integer and you multiply it by 2 before printing.
✗ Incorrect
The program reads the integer 7, then multiplies it by 2, printing 14.
❓ Predict Output
intermediate2:00remaining
What happens if non-integer input is given?
What will happen if the user inputs abc when running this Java code?
Java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int num = scanner.nextInt(); System.out.println(num); } }
Attempts:
2 left
💡 Hint
nextInt() expects an integer input.
✗ Incorrect
If the input is not an integer, nextInt() throws InputMismatchException.
🧠 Conceptual
advanced1:30remaining
Which Scanner method reads an integer from input?
You want to read an integer value from the user in Java. Which Scanner method should you use?
Attempts:
2 left
💡 Hint
Think about which method returns an int type.
✗ Incorrect
nextInt() reads the next token as an integer value.
📝 Syntax
advanced1:30remaining
Identify the syntax error in this integer input code
Which option contains a syntax error when trying to read an integer from input?
Java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int num = scanner.nextInt() System.out.println(num); } }
Attempts:
2 left
💡 Hint
Check punctuation at the end of statements.
✗ Incorrect
The line 'int num = scanner.nextInt()' is missing a semicolon at the end.
🚀 Application
expert2:30remaining
What is the value of 'sum' after reading two integers?
This Java program reads two integers from the user and sums them. If the user inputs 3 and then 5, what is the value of the variable
sum after execution?Java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int a = scanner.nextInt(); int b = scanner.nextInt(); int sum = a + b; System.out.println(sum); } }
Attempts:
2 left
💡 Hint
Sum means adding the two numbers, not concatenating.
✗ Incorrect
The program reads 3 and 5 as integers, sums them to 8, and prints 8.