시작 시간 (이 경우 9시)이 있고 여기에 특정 시간이 추가되고 현재 시간을 계산해야합니다. 내가 사용하는 현재 방법은 원래 시간에 경과 된 시간을 더한 다음 12로 모듈로를 추가하는 것입니다. 이렇게 timeAndHoursPassed % 12 = currentTime
하면 추가 된 시간을 12로 나눌 수있는 경우를 제외하고 모든 경우에 잘 작동합니다 . 이 경우 현재 시간을 얻습니다. 12 대신 0이됩니다. 어떻게 고칠 수 있습니까? 또한 가능하다면 GregorianCalender 클래스를 사용하는 대신 가능한 기본 수학을 사용하는 것을 선호합니다. 사전에 모든 도움에 감사드립니다. 내 코드는 다음과 같습니다.
package week11;
import java.util.Scanner;
public class PassingTrains {
static int currentTime = 9, firstDistance = 0, secondDistance = 0, firstSpeed = 40, secondSpeed;
static Scanner input = new Scanner(System.in);
public static String passTime(){
System.out.print("Enter the speed of the passenger train: ");
secondSpeed = input.nextInt();
while (currentTime < 11) {
firstDistance += firstSpeed;
currentTime++;
}
while (firstDistance > secondDistance) {
firstDistance += firstSpeed;
secondDistance += secondSpeed;
currentTime++;
}
if (firstDistance == secondDistance){
return ("at " + currentTime % 12);
} else {
return ("between " + (currentTime - 1) % 12 + " o'clock and " + currentTime % 12);
}
}
public static void main(String[] args) {
System.out.println("The passenger train passed the freight train at " + passTime() + " o'clock");
System.out.println("The freight train was traveling " + firstSpeed + " mph");
System.out.println("The passenger train was traveling at " + secondSpeed + " mph");
}
}
두 부분이 있습니다.
샘플 코드 :
currentTime += elapsedTime % 24;
if(currentTime > 12)
{
currentTime -= 12;
}
업데이트 : OP의 수정 된 코드
public class PassingTrains
{
static int currentTime = 9, firstDistance = 0, secondDistance = 0,
firstSpeed = 40, secondSpeed, elapsedTime;
static Scanner input = new Scanner(System.in);
public static String passTime()
{
System.out.print("Enter the speed of the passenger train: ");
secondSpeed = input.nextInt();
while (currentTime < 11)
{
firstDistance += firstSpeed;
currentTime++;
}
while (firstDistance > secondDistance)
{
firstDistance += firstSpeed;
secondDistance += secondSpeed;
elapsedTime++; // changed this
}
// added the next two lines
currentTime += elapsedTime % 24;
currentTime = (currentTime > 12) ? currentTime - 12 : currentTime;
if (firstDistance == secondDistance)
{
return ("at " + currentTime); // fixed this
}
else
{
return ("between " + ((currentTime - 1 == 0) ? 12 : currentTime - 1) + " o'clock and " + currentTime); \\fixed this
}
}
public static void main(String[] args)
{
System.out.println("The passenger train passed the freight train at "
+ passTime() + " o'clock");
System.out.println("The freight train was traveling " + firstSpeed
+ " mph");
System.out.println("The passenger train was traveling at "
+ secondSpeed + " mph");
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다