gpt4 book ai didi

java - 如何调用一个不返回任何内容的方法?

转载 作者:行者123 更新时间:2023-12-01 16:55:18 25 4
gpt4 key购买 nike

我正在尝试调用此方法,该方法从用户输入中输入坐标点。

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

但我不知道如何使其工作,因为它不需要 return 语句。

这是我从主方法中调用它的方式:

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

我希望将所有案例从 switch 语句转移到这个单独的方法中,但我什至无法让其中一个工作。我错过了什么?

最佳答案

Java中有一种声明方法的结构。来自 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.

所以,如果你需要声明没有任何返回类型的方法,你需要在第二个位置写void

在你的代码中

public static Result Case1(){

您需要返回返回类型Result。如果不想返回它 - 声明方法如下:

public static void Case1(){

关于java - 如何调用一个不返回任何内容的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33861488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com