Task 1 of 8 · 0 solved · 8 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

2.1 Input — reading a value

Lesson

Programs that read their input

Until now every program had its numbers written into the code, so it always printed the same thing. Real programs read their data. From now on the practice tasks give you a value through the Input box, and your program reads it — so the same program gives different answers for different inputs.


The two lines that do it

import java.util.Scanner;          // at the very top of the file

Scanner in = new Scanner(System.in);   // once, at the start of main
int n = in.nextInt();                  // read one whole number

Treat these as a recipe for now — you will learn exactly how they work later. What matters today: after in.nextInt() the value from the Input box is stored in n, and you use n like any other variable.

For text use in.next(); to read two numbers, call in.nextInt() twice.


▶ Try it: type a number into the Input box and run. Then change the number and run again — same program, different answer.



What does in.nextInt() do?


Where does the import java.util.Scanner; line go?


To read two numbers, you...


True or false?


The program below is run with 4 in the Input box. Type exactly what it prints.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        System.out.println(n * 2);
    }
}