Input in Java

Name the following:

  1. A package needed to import Scanner class.
    java.util
  2. A method that accepts a character through Scanner object.
    charAt()
  3. A package needed to import Stream Reader class.
    java.io
  4. A method that accepts an integer token through Scanner object.
    nextInt()

Write down the syntax with reference to Java Programming:

  1. To accept an integral value ‘p’ through Stream class.
    p = Integer.parseInt(in.readLine());
  2. To accept a fractional value (float) ‘m’ through Scanner class.
    m = sc.nextFloat();
  3. To accept a character ‘d’ through Stream class.
    d = in.readLine().charAt(0);
  4. To accept a fractional value ‘n’ in double data type through Stream class.
    n = Double.parseDouble(in.readLine());
  5. To accept a word ‘wd’ through Stream class.
    wd = in.readLine();
  6. To create a Scanner object.
    Scanner sc = new Scanner(System.in);

Differentiate between the following:

  1. nextInt() and nextFloat() methods.
    The nextInt() method is a member of the Scanner class that is used to input integers through keyboard. The nextFloat() method is a member of the Scanner class that is used to input fractional numbers (float) through keyboard.
  2. Syntax and Logical errors.
    The syntax errors are the errors that occur when the rules or the grammar of the programming language are not followed. The logical errors are the errors that is concerned with an error in planning the program’s logic.

Answer the following:

  1. What do you mean by Scanner class?
    The Scanner class allows the user to read values of various types. It is defined within the java.util package.
  2. What are the different ways to give inputs in a Java program?
    a) By using assignment statement
    b) By using function argument
    c) By using Input Stream Reader class
    d) By using Scanner class
  3. What is the use of the keyword import?
    The import keyword enables us to use classes from a given package in your program.
  4. What is a package? Give an example.
    A package is a collection of related classes and interfaces. Examples include java.lang, java.util, java.io.
  5. What is the use of the keyword import in Java Programming?
    The import keyword enables us to use classes from a given package in your program.
  6. What is a compound statement? Give an example.
    A compound statement is a collection of statements, enclosed in curly braces.
    Example:

    if(num >= 0){
        double s = Math.sqrt(num);
        System.out.println();
    }
  7. Write down the syntax to input a character through Scanner class with an example.
    Syntax:
    char <variable> = <Scanner object>.next().charAt(0);
    Example:
    char ch = sc.next().charAt(0);
  8. What do you understand by Runtime error? Explain with an example.
    The errors that occur while executing the program are called runtime errors.
    Example:
    In the statement p = (a + b) / c;
    Runtime error will occur when c = 0.
  9. What are the different types of errors that take place during the execution of a program?
    These errors may occur due to incorrect mathematical tasks or by entering incorrect data values at the time of inputs.
  10. Distinguish between:
    a) Testing and Debugging
    Testing is a process in which a program is validated. Testing is complete when all desired verification against specifications have been performed.
    Debugging is the process in which the errors in the program are removed. Debugging is finished when there are no errors and the program is ready for execution.
    b) Syntax error and Logical error
    Syntax error is the grammatical error in the statements. The program is unable to give the output.
    Logical error is the error in programming logic. The program doesn’t give the desired output.

Java Programming

Question 1: The time period of a simple pendulum is given by the formula T = 2π√(l / g). Write a program to calculate the time period of a simple pendulum by taking length and acceleration due to gravity (g) as inputs.

import java.io.*;
class Pendulum{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter length: ");
        double len = Double.parseDouble(br.readLine());
        System.out.print("Acceleration due to gravity: ");
        double g = Double.parseDouble(br.readLine());
        double t = 2 * 22.0 / 7 * Math.sqrt(len / g);
        System.out.println("Time period: " + t);
    }
}

Question 2: Write a program by using class Employee to accept basic pay of an employee. Calculate the allowances/deductions as given below:
Dearness Allowance (DA) = 30% of basic pay
House Rent Allowance (HRA) = 15% of basic pay
Provident Fund (PF) = 12.5% of basic pay
Gross Pay = Basic Pay + DA + HRA
Net Pay = Gross Pay – PF
Find and print the gross and net pay.

import java.io.*;
class Salary{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Basic Pay: ");
        double basic = Double.parseDouble(br.readLine());
        double da = 30.0 / 100 * basic;
        double hra = 15.0 / 100 * basic;
        double pf = 12.5 / 100 * basic;
        double gross = basic + da + hra;
        double net = gross - pf;
        System.out.println("Gross Pay: " + gross);
        System.out.println("Net Pay: " + net);
    }
}

Question 3: A shopkeeper offers 10% discount on the printed price of a digital camera. However, a customer has to pay 6% GST on the remaining amount. Write a program in Java to calculate the amount to be paid by the customer taking printed price as an input.

import java.io.*;
class Camera{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Printed price: ");
        double price = Double.parseDouble(br.readLine());
        double discount = 10.0 / 100 * price;
        double remaining = price - discount;
        double gst = 6.0 / 100 * remaining;
        double amount = remaining + gst;
        System.out.println("Amount to be paid: " + amount);
    }
}

Question 4: A shopkeeper offers 30% discount on purchasing articles whereas the other shopkeeper offers two successive discounts 20% and 10% for purchasing the same articles. Write a program in Java to compute and display the discounts. Take the price of an article as the input.

import java.io.*;
class Successive{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Price: ");
        double price = Double.parseDouble(br.readLine());
        double discount = 30.0 / 100 * price;
        double amount1 = price - discount;
        double discount1 = 20.0 / 100 * price;
        double amount2 = price - discount1;
        double discount2 = 10.0 / 100 * amount2;
        amount2 = amount2 - discount2;
        System.out.println("Amount 1: " + amount1);
        System.out.println("Amount 2: " + amount2);
    }
}

Question 5: Mr. Agarwal invests certain sum at 5% per annum compound interest for three years. Write a program in Java to calculate:
a) the interest for the first year.
b) the interest for the second year.
c) the amount after three years.
Take sum as an input from the user.
Sample Input: Principal = 5000, Rate = 10%, Time = 3 years.
Sample Output:
Interest for the first year: 500
Interest for the second year: 550
Interest for the third year: 605

import java.io.*;
class Compound{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Principal: ");
        double p = Double.parseDouble(br.readLine());
        double si = p * 5 * 1 / 100;
        System.out.println("Interest for the first year: " + si);
        p += si;
        si = p * 5 * 1 / 100;
        System.out.println("Interest for the second year: " + si);
        p += si;
        si = p * 5 * 1 / 100;
        System.out.println("Interest for the third year: " + si);
    }
}

Question 6: A businessman wishes to accumulate 3000 shares of a company. However, he already has some shares of that company valuing Rs. 10 (nominal value) which yield 10% dividend per annum and receive Rs. 2000 as dividend at the end of the year. Write a program in Java to calculate the number of shares he has and how many more shares to be purchased to meet his target.
Hint: Number of share = (Annual dividend × 100) / (Nominal value × Dividend%)

class Shares{
    public static void main(String args[]){
        int num = (2000 * 100) / (10 * 10);
        System.out.println("He has " + num + " shares.");
        int more = 3000 - num;
        System.out.println("He needs " + more + " more shares.");
    }
}

Question 7: Write a program to input the time in seconds. Display the time after converting them into hours, minutes and seconds.
Sample Input: Time in seconds = 5420
Sample Output: 1 hour 30 minutes 20 seconds

import java.io.*;
class Convert{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Number of seconds: ");
        int s = Integer.parseInt(br.readLine());
        int h = s / 3600;
        s %= 3600;
        int m = s / 60;
        s %= 60;
        System.out.println(h + " hours " + m + " minutes " + s + " seconds.");
    }
}

Question 8: Write a program to input two unequal numbers. Display the numbers after swapping their values in the variables without using a third variable.
Sample Input: a = 23, b = 56
Sample Output: a = 56, b = 23

import java.io.*;
class Swap{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("First number: ");
        int a = Integer.parseInt(br.readLine());
        System.out.print("Second number: ");
        int b = Integer.parseInt(br.readLine());
        a += b;
        b = a - b;
        a -= b;
        System.out.println("a = " + a + ", b = " + b);
    }
}

Question 9: A certain amount is invested at the rate 10% per annum for 3 years. Find the difference between compound interest and simple interest. Write a program to take amount as an input.
Hint: SI = P × R × T / 100
A = P × (1 + R / 100)T
CI = A – P

import java.io.*;
class Difference{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Amount: ");
        double p = Double.parseDouble(br.readLine());
        double si = p * 10.0 * 3 / 100.0;
        double ci = p * Math.pow((1 + 10.0 / 100), 3) - p;
        double diff = ci - si;
        System.out.println("Simple Interest: " + si);
        System.out.println("Compound Interest: " + ci);
        System.out.println("Difference = " + diff);
    }
}

Question 10: A shopkeeper sells two calculators for the same price. He earns 20% profit on one and suffers a loss of 20% on the other. Write a program to find the total cost price of the calculators by taking selling price as input.
Hint: CP = (SP / (1 + Profit / 100)) when there is profit.
CP = (SP / (1 – Loss / 100)) when there is loss.

import java.io.*;
class Calculator{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Selling price: ");
        double sp = Double.parseDouble(br.readLine());
        double cp1 = (sp / (1 + 20.0 / 100));
        double cp2 = (sp / (1 - 20.0 / 100));
        double tcp = cp1 + cp2;
        System.out.println("Total Cost Price = " + tcp);
    }
}

10 thoughts on “Input in Java

    • Scanner sc = new Scanner(System.in);
      System.out.print(“Integer: “);
      int i = sc.nextInt();
      System.out.print(“Double: “);
      double d = sc.nextDouble();
      System.out.print(“String: “);
      String s = sc.nextLine();
      System.out.print(“Float: “);
      float f = sc.nextFloat();
      System.out.print(“Character: “);
      char c = sc.next().charAt(0);

        • Just replace the import statement with import java.util.Scanner; and BufferedReader line with Scanner in = new Scanner(System.in); Also skip including throws IOException. And use in.nextInt(), in.nextLine(), in.nextDouble() accordingly.

Leave a Reply