gpt4 book ai didi

java - 调用非静态方法时遇到问题

转载 作者:行者123 更新时间:2023-12-02 02:50:07 24 4
gpt4 key购买 nike

我目前正在开展一个学校项目,我应该能够调用我的程序来调用一个非静态方法,该方法仍然可以向前和向后移动我当前的数字。我很茫然。我到底应该做什么?这是到目前为止我的编码,除了实现非静态选项之外,一切正常。

   import java.util.Scanner;

public class PictureViewer {

final static int MAX_NUMBER = 8;
final static int MIN_NUMBER = 1;


public static void main(String[] args) {
showMenu();
}

public static void showMenu() {
Scanner input = new Scanner(System.in);
int current_number = MIN_NUMBER;
boolean Continuation = true;
while (Continuation) {

System.out.println("Select One of the Options");
System.out.println("Option 1: Forward");
System.out.println("Option 2: Backward");
System.out.println("Option 3: CreateFileName");
System.out.println("Option 4: CreateRandomName");
System.out.println("Option 5: Non-Static Forward");
int Menu_Option = input.nextInt();
switch (Menu_Option) {
case 1:
current_number = forward(current_number);
System.out.println("The Current Number is: " + current_number);
break;
case 2:
current_number = backward(current_number);
System.out.println("The Current Number is: " + current_number);
break;
case 3:
String fileName = createFileName(current_number);
System.out.println("File Name: " + fileName);
break;
case 4:
fileName = createRandomName(current_number);
System.out.println("File Name: " + fileName);
break;


}
}
}

public static int forward(int current_number) {

if (current_number >= MAX_NUMBER) {
System.out.println(MIN_NUMBER);
current_number = MIN_NUMBER;

} else {
System.out.println(current_number++);
}
return current_number;
}

public static int backward(int current_number) {

if (current_number <= MIN_NUMBER) {
System.out.println(current_number);
current_number = MIN_NUMBER;
} else current_number --; {
}
return current_number;
}
public static String createFileName(int current_number) {

return "Picture" + current_number + ".gif";
}

public static String createRandomName(int current_number) {
current_number = MIN_NUMBER + (int) (Math.random() * MAX_NUMBER);
return "Picture" + current_number + ".gif";
}

public void forward () {
// overloaded method, use global variable as input and output
}

public void backward () {
// overloaded method, use global variable as input and output
}

}

最佳答案

您无需将所有方法定义为static 即可从main 调用。您可以在 main 中创建一个对象并调用相同的方法。这就是我要做的:

  1. 将所有方法(main 除外)设为非静态(即删除 static 关键字)
  2. 更改main方法实现以创建PictureViewer类的对象并调用showMenu,例如

    public static void main(String[] args) {
    new PictureViewer().showMenu();
    }

关于java - 调用非静态方法时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43986456/

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