swift 4.0.3 //Write a program that prompts a user for the current month and year
ID: 3879923 • Letter: S
Question
swift 4.0.3
//Write a program that prompts a user for the current month and year and for a month and year in the past. The program should //output how far in the past the past date is. The input and output should be something like:
// SAMPLE INPUT:
//Enter Past Month: 3
//Enter Past Year: 1997
//Enter Current Month: 01
//Enter Current Year: 2018
/*SAMPLE OUTPUT:
03-1998 was 21 year(s), 2 month(s) ago.
must use safe string to integer conversion for this exercise. the program should not crash under any circumstances (no matter the user’s input). the word “Optional” should not appear anywhere in the code’s output.
*/
import Foundation
print("Enter Past Month: ")
let userPastMonth = readLine()
print("Enter Past Year: ")
let userPastYear = readLine()
print("Enter Current Month:")
let userCurrentMonth = readLine()
print("Enter Current Year:")
let userCurrentYear = readLine()
Explanation / Answer
import Foundation
print("Enter past month: ")
let pastMonth = console_input().toInt()!
print("Enter past year: ")
let pastYear = console_input().toInt()!
print("Enter current month: ")
var currentMonth = console_input().toInt()!
print("Enter current year: ")
var currentYear = console_input().toInt()!
var timeYears = 0
var timeMonths = 0
if pastMonth > currentMonth {
timeYears = pastYear - currentYear - 1
timeMonths = (12 - pastMonth) + (currentMonth)
}
else {
timeYears = pastYear - currentYear
timeMonths = currentMonth - pastMonth
}
println("(pastMonth)-(pastYear) was (timeYears) year(s), (timeMonths) month(s) ago.")
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.