
Define a class named StepTracker with the following specifications: Member Variables: String name - stores the user’s name. int sw - stores the total number of steps walked by the user. double cb - stores the estimated calories burned by the user. double km - stores the estimated distance walked in kilometers. Member Methods: void accept() - to input the name and the steps walked using Scanner class methods only. void calculate() - calculates calories burned and distance in km based on steps walked using the following estimation table: Calories Burned : steps walked x 0.04 (e.g. 1 step burns 0.04 calories) Distance (Km) : steps walked / 1300 (e.g. 1300 steps is approx. 1 km) void display() - Display the calories burned, distance in km and the user’s name. Write a main method to create an object of the class and invoke the methods.
Topic: Class definition with calculations
Answer
import java.util.Scanner;
class StepTracker { String name; // name of the user int sw; // total steps walked double cb; // calories burned double km; // distance walked in kilometres
void accept() { Scanner sc = new Scanner(System.in); System.out.print("Enter your name : "); name = sc.nextLine(); System.out.print("Enter total steps walked : "); sw = sc.nextInt(); }
void calculate() { cb = sw * 0.04; km = sw / 1300.0; }
void display() { System.out.println("Name : " + name); System.out.println("Calories burned : " + cb); System.out.println("Distance walked : " + km + " km"); }
public static void main(String args[]) { StepTracker ob = new StepTracker(); ob.accept(); ob.calculate(); ob.display(); } }
A straightforward class-definition question, but one line decides the marks.
Write the division as sw / 1300.0, NOT sw / 1300. Both sw and 1300 are ints, so Java would perform integer division and throw away the fraction — 2600 steps would still give 2 km, but 1000 steps would give 0 km instead of 0.77. Making the divisor a double (1300.0) forces the whole expression into floating point. The calories line is safe because 0.04 is already a double.
Two other habits examiners look for: read the name with nextLine() rather than next(), since a name may contain a space; and follow the given variable names (name, sw, cb, km) exactly — the question specifies them, and renaming loses marks even if the logic is right.
Check with 2600 steps: cb = 2600 x 0.04 = 104.0 calories and km = 2600 / 1300.0 = 2.0 km.
name String - name of the user, entered from the keyboard sw int - total number of steps walked cb double - calories burned, computed as sw x 0.04 km double - distance in km, computed as sw / 1300.0 sc Scanner - object used to read input ob StepTracker - object of the class used in main()