0
0
Javaprogramming~20 mins

Reading integer input in Java - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Java Input Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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);
    }
}
A0
B7
CError: InputMismatchException
D14
Attempts:
2 left
💡 Hint
Remember that nextInt() reads an integer and you multiply it by 2 before printing.
Predict Output
intermediate
2: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);
    }
}
AProgram waits forever
BThrows InputMismatchException
CPrints 0
DPrints abc
Attempts:
2 left
💡 Hint
nextInt() expects an integer input.
🧠 Conceptual
advanced
1: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?
AnextInt()
BnextDouble()
CnextLine()
Dnext()
Attempts:
2 left
💡 Hint
Think about which method returns an int type.
📝 Syntax
advanced
1: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);
    }
}
AScanner class not imported
BUsing nextLine() instead of nextInt()
CMissing semicolon after scanner.nextInt()
DVariable num declared as String
Attempts:
2 left
💡 Hint
Check punctuation at the end of statements.
🚀 Application
expert
2: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);
    }
}
A8
B35
CError: InputMismatchException
D0
Attempts:
2 left
💡 Hint
Sum means adding the two numbers, not concatenating.