Final challenge: read, work, save
After this: Predict, complete and explain programs that take input, read files and use the standard library.
This challenge has five steps, and each step is scored on its own. You will predict what a program prints when a person types a line, write the line that converts typed text to a number, predict what a program prints from a two-line file, say where a program looks for a file, and write an import line. Every step shows the code in Python and in Java, and the answers are the same in both. You can try as many times as you like, and hints work as they do in the lessons.
Step 1 of 5Predict it
Predict it
The person types 7 and presses Enter. What does the program print, not counting what the person typed?
print("Number?")n = int(input())print(n * 2)import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.println("Number?"); int n = Integer.parseInt(keyboard.nextLine()); System.out.println(n * 2); }}Convert the text
Complete the missing line so that the typed text becomes a whole number in the box number. With 4 typed, the program prints 40.
print("Type a number:")text = input()____________________ # ← turn the text into a whole number, in the box numberprint(number * 10)import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.println("Type a number:"); String text = keyboard.nextLine(); ____________________ // ← turn the text into a whole number, in the box number System.out.println(number * 10); }}Read it back
The file people.txt holds two lines: ana and ben. What does the program print?
with open("people.txt") as f: lines = f.readlines()for line in lines: print(line.strip().upper())import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;
public class Main { public static void main(String[] args) throws IOException { List<String> lines = Files.readAllLines(Path.of("people.txt")); for (String line : lines) { System.out.println(line.toUpperCase()); } }}Where the file is
A program opens scores.txt by that name alone, with no folder in front. Where does it look for the file?
Bring in the tools
Write the missing first line so that the program can use random.randintRandom. It then prints one dice roll.
____________________ # ← bring in the random toolsprint(random.randint(1, 6))____________________ // ← bring in the Random toolpublic class Main { public static void main(String[] args) { Random dice = new Random(); System.out.println(dice.nextInt(1, 7)); }}- Predict what a program prints from typed lines and from a file, complete the converting line and the import line, and say where a program looks for a file.