Home » Java » java – How do I retrieve the data input from a scanner to use in a method?-Exceptionshub

java – How do I retrieve the data input from a scanner to use in a method?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

Basically I have to write a program that uses data that was inputted by the user and put it in a mathematical formula so it spits out an answer. The formula has to be created as a method. This is what I have so far. When I run the code it lets me input a number, but when I do that the program does not output anything and it just finishes running.

import java.util.Scanner;

public class Namek {
    static int myMethod(int radius) {
        return ((radius * radius) * (22/7));
    }

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter Radius");
        String radius = keyboard.nextLine();

    }

    private static void myMethod() {
    }
How to&Answers:

You need to call the method passing the radius as parameter of the method. You can check https://www.tutorialspoint.com/java/java_methods.htm
,this link to see how to create and call methods with parameters.

I think what you wanted to do is the following:

import java.util.*;
public class Namek {
        static int myMethod(int radius) {
            return ((radius * radius) * (22/7));
        }
        public static void main(String[] args) {
            Scanner keyboard = new Scanner(System.in);
            System.out.println("Enter Radius");
            int radius = Integer.valueOf(keyboard.nextLine());
            int area = myMethod(radius);
            System.out.println(area);
        }
}

Answer:

Below is what you were trying to do I think

public class Formula {
        static int myMethod(int radius) {
            return ((radius * radius) * (22/7));
        }

        public static void main(String[] args) {
            Scanner keyboard = new Scanner(System.in);
            System.out.println("Enter Radius");
            int radius = Integer.valueOf(keyboard.nextLine());
            float output = myMethod(radius);
            System.out.println(output);
        }

}