简体   繁体   English

如何调用不返回任何内容的方法?

[英]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. 但是我不知道如何使它工作,因为它不需要return语句。

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. 我希望将所有案例从switch语句转换为这种单独的方法,但我什至无法使其中的一种工作。 What am I missing? 我想念什么?

There is a structure of declaring methods in Java. 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. 返回类型-方法返回的值的数据类型;如果该方法未返回值,则返回void。
  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. 因此,如果需要声明不带任何返回类型的方法,则需要在第二个位置写入void

In your code 在你的代码中

public static Result Case1(){

there is return type Result that you need to return. 有需要返回的返回类型Result If don't want to return it - declare method like this: 如果不想返回它-声明这样的方法:

public static void Case1(){

When declaring a method that shouldn't return anything you must use void as the return type. 声明不应该返回任何内容的方法时,必须使用void作为返回类型。 In your case the return type is Result so it won't compile until you add a return statement returning a Result object. 在您的情况下,返回类型为Result,因此直到您添加返回Result对象的return语句,它才会编译。 More on defining methods: https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html 有关定义方法的更多信息: https : //docs.oracle.com/javase/tutorial/java/javaOO/methods.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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