在Main中调用String方法

时间:2017-01-30 19:56:58

标签: java class methods

我只是试图调用一个返回字符串的简单方法,出于某种原因,我在消隐,不记得我的生活如何正确地做到这一点。我试图在Bands类中调用方法getInfo()并打印出其中的字符串bandInfo:

public class App {


public static void main(String[] args) {

    Bands[] bands = new Bands[5];

    bands[0] = new Bands("Joe", "Rick", "Nick", "Dalton", "Doylestown, PA", "RockOn", 4000.50 , "Rock");
    bands[1] = new Bands("Luke", "Bill", "Ian", "Matt", "State College, PA", "Blink182", 3500.50 , "Alternative");
    bands[2] = new Bands("Corey", "Noah", "Jon", "Kaleb", "Philadelphia, PA", "Rise Against", 10000.50 , "Rock");
    bands[3] = new Bands("Jake", "Joey", "Mike", "Mac", "New York, NY", "Thousand Foot Krutch", 2000.50 , "Rock");
    bands[4] = new Bands("Bob", "Jeff", "Dom", "Mark", "King of Prussia, PA", "Skillet", 5500.50 , "Rock");

    bands[0].compete();
    bands[1].compete();
    bands[2].compete();
    bands[3].compete();
    bands[4].compete();

    for (int i = 0; i < 5; i++) {
        String bandInfo = getInfo(bandInfo);
    }
}
}

这是我的Bands类代码:

import java.util.Random;

public class Bands {

private String singerName;
private String guitarName;
private String bassistName;
private String drummerName;
private String Hometown;
private String bandName;
private double income;
private String genre;
private int score;

public Bands(String singerName, String guitarName, String bassistName, String drummerName, String Hometown, String bandName, double income, String genre)
{
    this.singerName = singerName;
    this.guitarName = guitarName;
    this.bassistName = bassistName;
    this.drummerName = drummerName;
    this.bandName = bandName;
    this.Hometown = Hometown;
    this.income = income;
    this.genre = genre;
    this.score = -1;
}

public void compete()
{     
    Random rand = new Random();
    this.score = rand.nextInt(20);

}

public String getInfo()
{
    String bandInfo = "Band: " + this.bandName + ", Singer: " + this.singerName + ", Guitarist: " + this.guitarName + ", Bassist: " + this.bassistName + 
                      ", Drummer: " + this.drummerName + ", Hometown: " + this.Hometown + ", Income: " + this.income + ", Genre: " + 
                      this.genre + ", Final Score: " + this.score;

    return bandInfo;
}
}

1 个答案:

答案 0 :(得分:2)

for (int i = 0; i < 5; i++) {
    String bandInfo = bands[i].getInfo();
}

getInfo()是Bands类的实例方法。 所以你必须使用Bands的一个实例来调用方法。

bands[i]指的是Bands对象。