-2

だから、私はJavaにかなり慣れていません。私は新しいのでかなり学びました。でも……もちろん、すべてを理解できるわけではありません。

私は2つのクラスを持っています。「Random」という名前の 1 つと「ananas」という名前の 1 つ (Ananas はフランス語でパイナップル)

ランダムは私のメイン クラスです...しかし、何らかの理由で私のメイン クラス (ランダム) は 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();」

しかし、コードを実行しようとしても、「ランダム」しか検出されません

助けてください?

4

2 に答える 2

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;
    }
于 2012-05-26T14:00:39.527 に答える
0

ananas にはコンストラクターがありません。

次のようなものが必要です。

public ananas(){
System.out.println("I like pineapples");
}

これが役立つことを願っています:)

于 2012-05-26T13:56:22.633 に答える