Skip to lesson

Mini programs and practice

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

A console program talks to the user through the terminal window, and almost every one follows the same pattern: prompt, read, calculate, print neatly. Plan one here, then build your own in the Problems part below.

The pattern of a console program

Before you type any code, answer three questions on paper: what does the user type, what do I calculate, and what should the result look like?

Then the program follows four steps: set up, prompt and read, calculate, print.

Example 1 · Bill calculator

Bill.javaJava
import java.util.Scanner;
public class Bill {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        System.out.print("Enter item, price and quantity: ");        String item = sc.next();        double price = sc.nextDouble();        int qty = sc.nextInt();        double total = price * qty;        System.out.printf("%d x %s = Rs. %.2f%n", qty, item, total);        sc.close();    }}
Sample output
Enter item, price and quantity: Biryani 180 2
2 x Biryani = Rs. 360.00

What this code does

  • Plan: the user types a word, a price and a count; the program multiplies; the result is one neat line.
  • Set up: import java.util.Scanner; at the top and one Scanner sc inside main.
  • Prompt and read: one prompt, then next(), nextDouble() and nextInt() take the three tokens in the order they were typed.
  • Calculate and print: price * qty uses the arithmetic operators (opens in a new tab), then printf fills %d, %s and %.2f and sc.close() ends it.

Output mistakes → fixes

These four slips cause most wrong-looking output. Each one links to the lesson that explains it.

Input mistakes → fixes

And these four cause most input trouble. The bug game (opens in a new tab) lets you practise spotting them.

Example 2 · Student ID card

IdCard.javaJava
import java.util.Scanner;
public class IdCard {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        System.out.print("Roll number: ");        int roll = sc.nextInt();        sc.nextLine();        System.out.print("Full name: ");        String name = sc.nextLine();        System.out.print("CGPA: ");        double cgpa = sc.nextDouble();        System.out.println("--- ID card ---");        System.out.printf("%-6s%d%n", "Roll:", roll);        System.out.printf("%-6s%s%n", "Name:", name);        System.out.printf("%-6s%.2f%n", "CGPA:", cgpa);        sc.close();    }}
Sample output
Roll number: 23
Full name: Sneha Patil
CGPA: 8.4
--- ID card ---
Roll: 23
Name: Sneha Patil
CGPA: 8.40

What this code does

  • sc.nextLine(); after the roll number throws away the line end, so the full name is not skipped.
  • %-6s gives each label 6 characters, so the values start in one column.
  • %.2f prints the CGPA 8.4 as 8.40.

Finish up

Mark complete & continue

Next: The if statement