[英]Asking for A User Input for Time using JOptionPane
我的老師要求我們通過使用JOptionPane輸入時間(HH,mm,ss)來要求用戶提供賽車手的開始時間和停止時間。 我不確定該怎么做。 我曾嘗試做integer.parseint(joptionpane ....),但輸入時間后仍會收到錯誤消息。 另外,我知道問題在於,由於我要用戶為我的Time類輸入一個時間,因此該時間應該有所不同。 從這一點開始,我需要一些幫助。 這是我的代碼(我還在其中包含了時間類:
package Racers.java;
import javax.swing.JOptionPane;
public class Racers
{
public static void main(String[] args)
{
//racer1
String racer1;
Time startTime1;
Time stopTime1;
double elapsedTime1;
//assigning racer1
racer1 = JOptionPane.showInputDialog("Please enter the name of the first racer: ");
startTime1 = new Time();
stopTime1 = new Time();
elapsedTime1 = stopTime1.minus(startTime1).getTime();
JOptionPane.showMessageDialog(null,
"Here is the racer's name, start time, stop time, and elapsed time:\n"
+ racer1 + (" - ") + ("Start time: ") + startTime1 + ("; ") + ("Stop time: ") + stopTime1 + ("; ") + ("Elapsed time: ") + elapsedTime1 + "\n"
}//End main
}//End Racers
class Time
{
//Variable to hold seconds
double seconds;
//Constructors for class Time
public Time()
{
seconds = 0.0;
}
public Time(double newSeconds)
{
seconds = newSeconds;
}
public Time(int hours, int minutes, double newSeconds)
{
seconds = (double)(hours * 3600 + minutes * 60) + newSeconds;
}
//Observers for class Time
public double getTime()
{
//Return elapsed time
return seconds;
}
public int getHours()
{
//Compute whole hours from seconds
return (int)seconds / 3600;
}
public int getMinutes()
{
//Seconds after hours taken out
int remainingSeconds = (int)seconds % 3600;
//Compute minutes from remainder
return remainingSeconds / 60;
}
public double getSeconds()
{
//Seconds after minutes taken out
return seconds % 60.0;
}
//Returns HH:MM:SS.FFF
public String toString()
{
int hours = (int)seconds / 3600;
int minutes = (int)seconds % 3600 / 60;
return hours + ":" + minutes + ":" + seconds % 60.0;
}
//Operations for class Time
public Time plus(Time otherTime)
{
return new Time(seconds + otherTime.seconds);
}
public Time minus(Time otherTime)
{
return new Time(seconds - otherTime.seconds);
}
}//End Time
這是問題
startTime1 = new Time();
stopTime1 = new Time();
您正在使用默認構造函數初始化開始和停止時間,其中默認構造函數將開始和停止時間返回為零,因此輸出也為零。
因此,您需要使用參數化構造函數來區分時間。
即
startTime1 = new Time(10,10,10d); // 10hr 10 min 10 sec
stopTime1 = new Time(10,20,10d); //10hr 20 min 10 sec
那么您發現10分鍾的時間差就是600秒。
也使用下面的行
JOptionPane.showMessageDialog(null, "Here is the racer's name, start time, stop time, and elapsed time:\n" + racer1 + (" - ") + ("Start time: ") + startTime1 + ("; ") + ("Stop time: ") + stopTime1 + ("; ") + ("Elapsed time: ") + elapsedTime1 + "\n");
希望你能理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.