对于Java来说我还是一个相对较新的人,但是我现在面临的问题是我一直在使用当前的东西时遇到编译时错误。
我不确定是否存在一种特殊的逻辑结构,该逻辑结构将从文件中获取现有值并转换为数字格式。
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.time.Duration;
public class Music {
// Method header
public static void main(String [] args) throws IOException{
// Variable declarations
String id;
String artistName;
String title;
String releaseName;
int year;
double endOfFadeIn;
double startOfFadeOut;
double loudness;
double duration;
// Scanner to read input from the user
Scanner keyboard = new Scanner(System.in);
// Scanner to read in the file that the user types.
System.out.print("Enter the name of the file: ");
String filename = keyboard.nextLine();
File inFile = new File(filename);
Scanner fileScan = new Scanner(inFile);
fileScan.useDelimiter(",|\\r?\\n");
fileScan.nextLine();
// Read from file using Scanner
while(fileScan.hasNext()) {
id = fileScan.next();
System.out.println(id);
id = formatID(id);
System.out.println(id);
artistName = fileScan.next();
System.out.println(artistName);
artistName = truncate(artistName);
title = fileScan.next();
System.out.println(title);
title = truncate(title);
releaseName = fileScan.next();
System.out.println(releaseName);
releaseName = truncate(releaseName);
year = fileScan.nextInt();
System.out.println(year);
endOfFadeIn = fileScan.nextDouble();
System.out.println(endOfFadeIn);
startOfFadeOut = fileScan.nextDouble();
System.out.println(startOfFadeOut);
loudness = fileScan.nextDouble();
System.out.println(loudness);
System.out.printf("%-10s %-20s %-20s %-20s%n", id, artistName, title,
releaseName);
}
}// end main
public static String formatID(String id) {
String newid;
newid = id.substring(0,7) + "-" + id.substring(7,9) + "-" + id.substring(9,18);
return newid;
}//end formatID
public static String truncate(String str){
if (str.length() > 20) {
return str.substring(0, 20-3) + "...";
} else {
return str;
}
}//end truncateStr
public static String formatTime(double duration) {
int days=0;
int hours=0;
int minutes=0;
int seconds=0;
String Result;
Result = System.out.printf("%03s:%02s:%02s:%02s", days, hours, minutes, seconds);
string.format
System.out.printf("%03s:%02s:%02s:%02s", days, hours, minutes, seconds);
duration = (int) duration;
duration = (startOfFadeOut - endOfFadeIn);
duration = Math.round(duration);
}//end formatTime
}//end class
预期结果是,当从文件中读取值时,输出将以DD:HH:MM:SS格式显示时间。
答案 0 :(得分:0)
您没有指定是什么编译时错误或者是代码的哪一行导致了此错误,但是由于您发布了MRE,因此我只需要复制代码即可发现它是什么。 。就是这一行:
String Result;
Result = System.out.printf("%03s:%02s:%02s:%02s", days, hours, minutes, seconds);
方法printf返回一个PrintStream
而不返回一个String
。如果要使用String
,请使用方法format
所以您的代码应该是...
String Result;
Result = String.format("%03s:%02s:%02s:%02s", days, hours, minutes, seconds);
System.out.printf(Result);
此外,根据java coding conventions,变量名称(例如Result
)应以小写字母开头,即result
。