Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Step Counter Issue

I’m trying to write a step counter for one of my LAB assignments.

A pedometer treats walking 1 step as walking 2.5 feet. Define a method named feetToSteps that takes a double as a parameter, representing the number of feet walked, and returns an integer that represents the number of steps walked. Then, write a main program that reads the number of feet walked as an input, calls method feetToSteps() with the input as an argument, and outputs the number of steps.

Use floating-point arithmetic to perform the conversion.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Ex: If the input is:

150.5

the output is:

60

The code I have written is

import java.util.Scanner;

public class LabProgram {
   
   public static double feetToSteps(int userFeet) {
        return userFeet / 2.5;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print(feetToSteps(in.nextInt()));
    }
}

But the output I get with input of 150.5 is

Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
    at LabProgram.main(LabProgram.java:11)

It looks like my input is not matching what it is expecting. I am assuming I need it to recognize the input can be a float, but I’m not sure if I’m on the right line of thinking. Any suggestions?

>Solution :

You are calling in.nextInt(), so it is expecting the input in the console to be an integer. However, you are entering 150.5, which is a double. So, you should use nextDouble instead of nextInt.

You will also need to change the type of the parameter userFeet in feetToSteps from int to double, and change the return type from double to int, and cast the return value.

The full fixed code:

import java.util.Scanner;

public class LabProgram {
   
   public static int feetToSteps(int userFeet) {
        return (int) (userFeet / 2.5);
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print(feetToSteps(in.nextDouble()));
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading