所以,我对Java很新。我学到了很多新东西。但是......我当然不明白一切。
我有2节课。一个名为“随机”,一个名称为“凤梨”(Ananas是Pineapple的法语)
Random是我的主要类......但由于某种原因,我的主类(Random)没有检测到ananas。
这是我在ananas中的脚本:
public class ananas {
public String a(String PackageA){
PackageA = "This file shall remain TOP SECRET! The ultimate universal secret code is...'Ananas'";
return PackageA;
}
public String b(String PackageB){
PackageB = "File not created yet";
return PackageB;
}
public String c(String PackageC){
PackageC = "File not created yet";
return PackageC;
}
}
这是我在“随机”中的代码:
import java.util.Scanner;
public class Random {
public static void main(String ars[]){
Scanner input = new Scanner(System.in);
System.out.println("Welcome, Please enter the code: ");
String hey = input.nextLine();
if(hey .equals("The sandman ate my dollar"))
System.out.println("Welcome! Please choose one: A), B), C)");
Scanner input2 = new Scanner(System.in);
String heyy = input2.nextLine();
if(heyy .equals("A)"))
System.out.println("File not created yet");
else if(heyy .equals("B)"))
System.out.println("Flid not created yet");
else if(heyy .equals("C)"))
System.out.println("File not created yet");
else
System.out.println("Access Denied");
我试图这样做:“ananas abc = new ananas();”
但即使我去运行我的代码,它也只能检测到“随机”
请帮帮忙?
答案 0 :(得分:1)
如果这是您在Random中拥有的所有代码,那么您永远不会构建ananas的实例。 由于Ananas中的方法不是静态的,因此需要创建类的实例。
Ananas a = new Ananas(); // Construct new instance calling the default constructor
// Note that you have named your methods so that nobody can really understand what they do!
// Now, to call methods from this class, you would do it like this
//First a = the instance of ananas class we just built. The second a is the method in the class we wish to call. String is the parameter the method requires.
a.a(string);
因为它看起来你想根据用户提供的输入调用Ananas类中的方法,你可以修改你的代码来做这样的事情。
if(heyy.equals("A)"){
a.a(yourString); // You need to create the ananas instance before this, and have a string called yourString that you pass on to the method
}
在这种情况下,更好的解决方案是,不要求ananas中的方法需要String参数。还要考虑命名方法,以便描述它正在做什么!所需的更改将如此简单:
public String a(){ // a could be something like 'getStringA'
String PackageA = "This file shall remain TOP SECRET! The ultimate universal secret code is...'Ananas'";
return PackageA;
}
答案 1 :(得分:0)
我在ananas中看不到构造函数。
应该有类似的东西:
public ananas(){
System.out.println("I like pineapples");
}
我希望这会有所帮助:)