陷入方法/类参考问题(JAVA Basic)

时间:2016-11-05 04:45:54

标签: java function class methods reference

我的目标是创建一些代码,允许我的计算机随机选择它对我的意义。 "你好" +(随机选择的昵称)+",今天你好吗?"

非常简单,对吧?不是像我这样的菜鸟!

引用类 我给了它4个名字选择,它随机选择一个并打印出来。

public class NameRef {

     public static void main(String[] args){

        ArrayList<String> nickNames = new ArrayList<String>();
        nickNames.add("DJ");
        nickNames.add("Buddy");
        nickNames.add("Dude");
        nickNames.add("Sir");

        Random rand = new Random(); 
        rand.nextInt(4);

        System.out.println(nickNames.get(rand.nextInt(4)));
    }
}

主要类 我希望这个班级能够从中学课程中获取信息。在我的问候中功能和参考。

public class CodeTesting extends NameRef {

    public static void main(String[] args) {
        System.out.println("Hello, " + /*The product from the NameRef*/  + " how are you?");
    }
}

我不知道我应该如何引用这些信息?我尝试了一百种方法!

我还尝试在辅助类中创建一个返回名称字符串的函数,但后来我无法在我的主类中引用它...

我很困惑。关于我出错的地方的任何帮助都会很棒。感谢。

2 个答案:

答案 0 :(得分:1)

main中的NameRef更改为返回String的函数。因此,应该System.out.println(nickNames.get(rand.nextInt(4)));代替return nickNames.get(rand.nextInt(4))而不是CodeTesting。然后在public class CodeTesting extends NameRef { public static void main(String[] args) { System.out.println("Hello, " + nameOfFunction() + " how are you?"); } } 类中,调用这样的函数:

nameOfFunction

其中public String stretch(String s, int n){ char first = s.charAt(0); char last = s.charAt(s.length()-1); String result = ""; for(int i = 1; i < s.length()-2; i++) for(int j = 0; j < n; j++) result += first +s.charAt(i)+ last; return first +result+ last; 是您调用您创建的函数的名称

答案 1 :(得分:0)

public class NameRef {

     public String getName(){

        ArrayList<String> nickNames = new ArrayList<String>();
        nickNames.add("DJ");
        nickNames.add("Buddy");
        nickNames.add("Dude");
        nickNames.add("Sir");

        Random rand = new Random(); 
        rand.nextInt(4);

        return nickNames.get(rand.nextInt(4));
    }
}

public class CodeTesting extends NameRef {

    public static void main(String[] args) { 
       NameRef nameRefObject = new NameRef();
        System.out.println("Hello, " +nameRefObject.getName()+ " how are you?");
    }
}