Matt123
Matt123

Reputation: 615

How to call a method that doesn't return anything?

I'm trying to call this method that enters a coordinate point from user input.

public class Cases {

public static Result Case1(){
    Scanner in = new Scanner(System.in);
    System.out.println("Enter index: ");
    int i = in.nextInt(); //validate
    System.out.print("Enter integers x, y to replace: ");
    int x = in.nextInt();
    int y = in.nextInt();
    A[i] = new Point(x, y);

    if(occupancy<i)
        occupancy=i;
    }
}

but I don't know how to make it work since it doesn't need a return statement.

This is how I called it from my main method:

Result r = null;
r = Cases.Case1();

I want all of my cases from a switch statement into this separate method, but I can't even get one of them to work. What am I missing?

Upvotes: 0

Views: 12856

Answers (2)

user5593085
user5593085

Reputation:

When declaring a method that shouldn't return anything you must use void as the return type. In your case the return type is Result so it won't compile until you add a return statement returning a Result object. More on defining methods: https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html

Upvotes: 1

LEQADA
LEQADA

Reputation: 1982

There is a structure of declaring methods in Java. From documentation

... method declarations have six components, in order:

  1. Modifiers—such as public, private, and others you will learn about later.
  2. The return type—the data type of the value returned by the method, or void if the method does not return a value.
  3. The method name—the rules for field names apply to method names as well, but the convention is a little different.
  4. The parameter list in parenthesis—a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses.
  5. An exception list—to be discussed later.
  6. The method body, enclosed between braces—the method's code, including the declaration of local variables, goes here.

So, if you need to declare method without any return type, you need to write void in second position.

In your code

public static Result Case1(){

there is return type Result that you need to return. If don't want to return it - declare method like this:

public static void Case1(){

Upvotes: 4

Related Questions