如何在数组中调用存储的数据(字符串)?

时间:2016-10-06 04:33:06

标签: java arrays jgrasp

我正在尝试打印标题。

import java.text.SimpleDateFormat;
public class TheMixtape
{
 private String Title; 
 private String Artist;
 private String Genre;
 private int Minutes;
 private int Seconds;
 private int Duration;
 public TheMixtape()
 {
  String Title[]={"BROCCOLI", "Ready Set Go(VLone)", "Chill Bill", "Rara", "Too Much Sauce", "Heathens", "No Heart", "Water", "Wake Up"};
  String Artist[]={"Big Baby D.R.A.M.(Prod. By. J Gramm)", "Lil Uzi Vert", "Rob Stone", "Travis Scott ft(Lil Uzi Vert)", "Future","21 Pilots", "21 Savage", "Ugly God", "Fetty Wap"};
  String Genre[]={"Hip-Hop/Rap", "Trap Anthem", "Smooth Jazz", "Pop Music", "Trap Anthem", "Pop Song", "Rap", "Trap/Rap/Pop", "Pop"};
  //int D[]={ 3:45, 3:42, 2:57, 3:07, 3:38, 3:11, 3:55, 2:19, 3:44};   ignore this
  }
  public String getTitle()
  {
  return Title;
  }



  public static void main(String[]args)
 {
   TheMixtape Info = new TheMixtape();
   System.out.println("   Title     "+"Artist     "+"Genre     "+"Duration");
   for (int k=0;k<10;k++)
{
System.out.print(Info.getTitle());
   }
} 
 }

我希望能够说出像

Info.getTitle(1)

然后它会给我一个名为BROCCOLI的数组中的第一个字符串。 我该怎么做

1 个答案:

答案 0 :(得分:2)

将getTitle()更改为

  public String getTitle(int index)
  {
     return Title[index];  // the user will have to pass zero-based index
  }

注意

数组应该是类的一部分。你在构造函数中声明了它们,此时它们超出范围而无法使用。

public class TheMixtape{
String Title[]={"BROCCOLI", "Ready Set Go(VLone)", "Chill Bill", "Rara", ...};
String Artist[]={"Big Baby D.R.A.M.(Prod. By. J Gramm)", "Lil Uzi Vert", ...};
String Genre[]={"Hip-Hop/Rap", "Trap Anthem", "Smooth Jazz", "Pop Music"...};

public TheMixtape()
{
}

此外,Java编程标准通常使用与方法相同的大小写规则,例如:

String title[]={"BROCCOLI", "Ready Set Go(VLone)", ...};