0
0
Javaprogramming~10 mins

Reading integer input in Java - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
AnextLine
BnextDouble
CnextInt
Dnext
Attempts:
3 left
💡 Hint
Common Mistakes
Using nextLine() which reads a whole line as a string.
Using nextDouble() which reads a decimal number.
2fill in blank
medium

Complete 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'
Areader
Binput
Ckeyboard
Dscanner
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name that conflicts with class names.
Using reserved keywords as variable names.
3fill in blank
hard

Fix 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'
AnextDouble
BnextInt
CnextLine
DnextFloat
Attempts:
3 left
💡 Hint
Common Mistakes
Using nextLine() and trying to assign to int causes errors.
Using nextDouble() when expecting an integer.
4fill in blank
hard

Fill 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'
Ascanner
Binput
Creader
Dkeyboard
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently.
Forgetting to create the Scanner object.
5fill in blank
hard

Fill 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'
Ascanner
Binput
Creader
Dkeyboard
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names for reading inputs.
Not creating the Scanner object before reading.