User Interaction

User interactions using terminal.

Code Review Problem

  • The program will read data from console in the format below and print out the number of reams of paper that should be charged to that person. A ream is 500 pieces of paper and so number of reams should be rounded up.
  • Input Format:
    • <Number-of-pages> pages printed by <<name-of-person>
  • For example: When user enters “650 pages printed by Sonic the Hedgehog”, this should be printed to the console: “Sonic the Hedgehog: 2 ream(s)”
  • Read the code written and answer the question by selecting best option

Question 1

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    int numberOfReams = 0;
    final int PAGES_PER_REAM = 500;
    int numberOfpages = keyboard.nextInt();
    String personsName = keyboard.nextLine();
    numberOfReams = (int)Math.ceil((double)numberOfpages / PAGES_PER_REAM);
    System.out.println(personsName + ": " + numberOfReams + " ream(s)");
    keyboard.close();
}

Which one of the following is true about the given section of code?

a) Code will correctly print the expected output

b) double cast of numberOfPages is not needed

c) keyboard.nextLine() is not reading the person’s name correctly

d) Math.ceil() should be Math.round()

Question 2

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    final int PAGES_PER_REAM = 500;
    int numOfpages = keyboard.nextInt();
    keyboard.next();
    String personsName = keyboard.nextLine();
    int numberOfReams = (int)Math.ceil((double)numOfpages / PAGES_PER_REAM);
    System.out.println(personsName + ": " + numberOfReams + " ream(s)");
}

Which one of the following is true about the given section of code?

a) Code will correctly print the expected output

b) Person’s name will be printed incorrectly

c) numberOf Reams is off by one

d) keyboard.next() result must be assigned to a variable

Question 3

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    final int PAGES_PER_REAM = 500;
    int numOfpages = keyboard.nextInt();
    keyboard.next(); keyboard.next(); keyboard.next();
    String personsName = keyboard.nextLine();
    int numberOfReams = (int)Math.ceil(numOfpages / (double)PAGES_PER_REAM);
    System.out.println(personsName + ": " + numberOfReams + " ream(s)");
}

Which one of the following is true about the given section of code?

a) Code will correctly print the expected output

b) double cast of PAGES_PER_REAM is not needed

c) int cast for the Math.ceil method is not needed

d) keyboard.next() should not be called 3 times