gpt4 book ai didi

java - 基本Java : How to call a method?

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

我正在尝试创建一个包含菜单的程序,并将执行用户选择的任何选择。我完成了这些方法并让它们进行编译,但不知道如何调用这些类。以下是屏幕截图中的代码,以便更容易阅读:

极客类:(包含所有方法)

    public class Geek{
private String name;
private int numberofQuestions=0;

public Geek (String name){
this.name = name;
numberofQuestions = 0;

}
public String getName(){
return name;

}
public int getnumberofQuestions(){
return numberofQuestions;
}
public boolean allTheSame(int num1, int num2, int num3){

numberofQuestions++;
if(num1 == num2 && num2 == num3 && num1 == num3){
return true;}
else return false;
}
public int sum (int num1, int num2){
numberofQuestions++;
int largest = Math.max(num1, num2);
int smallest = Math.min(num1, num2);
int result =0;
for (int i=smallest; i <= largest;i++){
result = result + i;}
return result;

}
public String repeat(String str, int n){
numberofQuestions++;
String repetition = "";
for (int j=0; j < n; j++){
repetition = repetition + str;}
return repetition;

}


public boolean isPalindrome(String str){
numberofQuestions++;
int n = str.length();
for( int i = 0; i < n/2; i++ )
if (str.charAt(i) != str.charAt(n-i-1)) return false;
return true;
}

}

主要:

/image/E2z3a.png

编辑:我在这部分代码中遇到找不到符号错误:

case "d":
myGeek.sum(num1, num2, num3);
System.out.println("Enter the first number");
int num1 = scan.nextInt();
System.out.println("Enter the second number");
int num2 = scan.nextInt();
System.out.println("Enter the third number");
int num3 = scan.nextInt();
break;

最佳答案

类不会被调用,它们是创建对象的蓝图。

您需要一个程序入口点,在本例中是在您的类中,如下所示

public static void main(String[] args)
{
Geek myGeekObject = new Geek("Your name");
}

然后您可以调用创建的对象上的方法

public static void main(String[] args)
{
Geek myGeekObject = new Geek("Your name");
String geekName = myGeekObject.getName();
}

关于java - 基本Java : How to call a method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19730622/

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