import java.util.*;
import java.text.*;
import java.io.*;
public class AvgTime {
static double hrs1;
static double min1;
public static void main(String[] args) throws InterruptedException, FileNotFoundException {
Scanner in = new Scanner(System.in);
System.out.print("How many times? ");
int numOfTimes = in.nextInt();
double hrTotal = 0;
double minTotal = 0;
for (int i = 1; i <= numOfTimes; i++){
System.out.println("\nEnter time in military time notation: ");
System.out.print("Hour ");
double hrs1 = in.nextDouble();
System.out.print("Minute ");
double min1 = in.nextDouble();
hrTotal += hrs1;
minTotal += min1;
}
//calculate average
double avgHr1 = hrTotal/numOfTimes;
double timeMin1 = Math.round(minTotal/numOfTimes);
DecimalFormat df = new DecimalFormat("###");
String hours = df.format(avgHr1);
String minutes = df.format(timeMin1);
String time = hours+":"+minutes+":"+00;
String mt = hours+minutes;
SimpleDateFormat fmtMil = new SimpleDateFormat("HH:mm:ss");
Date inDate = fmtMil.parse(time, new ParsePosition(0));
SimpleDateFormat fmtAMPM = new SimpleDateFormat("hh:mm:ss aa");
StringBuffer outDate = fmtAMPM.format(inDate, new StringBuffer(), new FieldPosition(0));
System.out.println("\nThe average time is " + outDate+"\n"+mt+" in military time.\n\n");
String copy = "Copying...";
Thread.sleep( 550 );
for( int i = 0; i < copy.length(); i++ ) {
System.out.print(copy.charAt( i ) );
try{ Thread.sleep( 105 ); }catch( Exception e ){}
}
PrintWriter p = new PrintWriter("Times.txt");
p.println(hrs1+min1);
p.close();
System.out.println("\nDone\n\n\n");
Thread.sleep( 550 );
}
}
我希望它将用户输入的时间导出到文件中。例如,如果用户将numOfTimes设置为2,则hrs1和min1会有2个不同的值。
假设他们输入:1629和2018。
我希望文本文件像1629一样显示hrs1(16)和min1(29)。但是当我放入hrs1 + min1时,它不会输出'hrs1 + min1',而只是输出'0.0'。我只希望它导出“ 1629”和“ 2018”
。
为什么会这样,我该如何解决?
输出量
How many times? 2
Enter time in military time notation:
Hour 16
Minute 29
Enter time in military time notation:
Hour 20
Minute 18
应该出口什么:
1629
2018
最佳答案
有两个主要的修改,以使此代码起作用。首先,必须在循环外部声明和实例化PrintWriter
。并且对println
的调用必须在循环内部进行。其次,在打印之前,必须将double
转换为String
并适当地子字符串化。
Scanner in = new Scanner(System.in);
System.out.print("How many times? ");
int numOfTimes = in.nextInt();
double hrTotal = 0;
double minTotal = 0;
PrintWriter p = new PrintWriter("Times.txt");
for (int i = 1; i <= numOfTimes; i++) {
System.out.println("\nEnter time in military time notation: ");
System.out.print("Hour ");
double hrs1 = in.nextDouble();
System.out.print("Minute ");
double min1 = in.nextDouble();
hrTotal += hrs1;
minTotal += min1;
String hrs = String.valueOf(hrs1);
String min = String.valueOf(min1);
p.println(hrs.substring(0, hrs.indexOf(".")) + min.substring(0,min.indexOf(".")));
}
p.close();
在进行此更改之前,您的代码使用实际算术添加了两个双精度
hrs1
和mins1
,并且使用了您在类顶部声明的静态变量。static double hrs1;
static double min1;
您应该删除这些静态双打,因为它们实际上从未使用过。因为对
println
的调用在循环之外,所以导致引用了静态双精度值,而不是在循环内声明并分配了hrs1
和mins1
。您以为您使用的是在循环中声明的locals变量,但它们从未在范围内。