简体   繁体   中英

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.

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?

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()));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM