该程序的目的是从文件中获取有关音乐 Collection 的信息并将其转换为三个数组。
>4
>141 Pure Heroine:Lorde
>171 Lights Out:Ingrid Michaelson
>270 Unorthodox Jukebox :Bruno Mars
>190 Head Or Heart:Christina Perri
在文件中,4 代表数组的长度,数字是一个数组,专辑标题是另一个数组,艺术家姓名是最终的数组。标题和艺术家姓名的数组由冒号分隔。虽然我可以为数字创建数组,但给我带来麻烦的是如何为名称和标题创建单独的数组。我知道我必须将其转换为字符串并使用冒号作为分隔符,但我不确定如何转换。
import java.util.*;
import java.io.*;
public class tunes {
public static void main(String[] args) throws FileNotFoundException {
int size; //Determines the size of the arrays
Scanner input = new Scanner(new File("music.txt"));
size = input.nextInt();
int[] time = new int[size];
for (int i = 0; i < time.length; i++) { // Creates an array for the numbers
time[i] = input.nextInt();
input.nextLine();
}
String[] artist = new String[size];
for (int i = 0; i <artist.length; i++) {
while (input.hasNextLine()){
}
}
System.out.println();
System.out.println("TOTAL TIME\t\t\t\t" + calcTotalTime(time));
System.out.println();
System.out.println();
System.out.println("LONGEST TRACK");
System.out.println("-------------");
System.out.println();
System.out.println();
System.out.println("SHORTEST TRACK");
System.out.println("--------------");
}
public static void printTable(int[] time, String[] artist, String[] title) {
System.out.println("TITLE\t\t\t" + "ARTIST\t\t\t " + "TIME");
System.out.println("-----\t\t\t" + "------\t\t\t " + "----");
for (int i = 0; i < time.length; i++) {
System.out.println(title[i] + "\t" + artist[i] + "\t" + time[i]);
}
}
public static int calcTotalTime(int[] time) {
int sum = 0;
for (int i = 0; i < time.length; i++) {
sum = sum + time[i];
}
return sum;
}
public static int findLongest(int[] time) {
int longest = 0;
for (int i = 1; i < time.length; i++) {
if (time[i] > time[longest]) {
longest = i;
}
}
return longest;
}
public static int findShortest(int[] time) {
int shortest = 0;
for (int i = 1; i < time.length; i++) {
if (time[i] < time[shortest]) {
shortest = i;
}
}
return shortest;
}
}
输出的示例如下
>Pure Heroine Lorde 141
>Lights Out Ingrid Michaelson 171
>Unorthodox Jukebox Bruno Mars 270
>Head or Heart Christina Perri 190
最佳答案
您可以在文本上使用 String.split(":")
将艺术家/标题 String
拆分为 String[]
数组。
例如:
System.out.println(Arrays.toString("Head Or Heart:Christina Perri".split(":")));
输出
[Head Or Heart, Christina Perri]
关于java - 将信息读入多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23497891/