|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "time" |
| 6 | +) |
| 7 | + |
| 8 | +// Mobile struct represents a mobile device. |
| 9 | +type Mobile struct { |
| 10 | + Brand string |
| 11 | + Model string |
| 12 | + IsOn bool |
| 13 | + Battery int |
| 14 | + LastUsage time.Time |
| 15 | +} |
| 16 | + |
| 17 | +// TurnOn turns on the mobile device. |
| 18 | +func (m *Mobile) TurnOn() { |
| 19 | + m.IsOn = true |
| 20 | + m.LastUsage = time.Now() |
| 21 | + fmt.Printf("%s %s is now turned on.\n", m.Brand, m.Model) |
| 22 | +} |
| 23 | + |
| 24 | +// TurnOff turns off the mobile device. |
| 25 | +func (m *Mobile) TurnOff() { |
| 26 | + m.IsOn = false |
| 27 | + fmt.Printf("%s %s is now turned off.\n", m.Brand, m.Model) |
| 28 | +} |
| 29 | + |
| 30 | +// UseMobile simulates the usage of the mobile device. |
| 31 | +func (m *Mobile) UseMobile(minutes int) { |
| 32 | + if !m.IsOn { |
| 33 | + fmt.Println("Please turn on the mobile device first.") |
| 34 | + return |
| 35 | + } |
| 36 | + |
| 37 | + if m.Battery <= 0 { |
| 38 | + fmt.Println("The mobile device is out of battery. Please charge it.") |
| 39 | + return |
| 40 | + } |
| 41 | + |
| 42 | + m.LastUsage = time.Now() |
| 43 | + fmt.Printf("Using %s %s for %d minutes.\n", m.Brand, m.Model, minutes) |
| 44 | + |
| 45 | + // Simulate battery drain |
| 46 | + m.Battery -= minutes |
| 47 | + if m.Battery < 0 { |
| 48 | + m.Battery = 0 |
| 49 | + } |
| 50 | + |
| 51 | + // Check battery level |
| 52 | + if m.Battery == 0 { |
| 53 | + m.TurnOff() |
| 54 | + fmt.Println("The mobile device is out of battery. Please charge it.") |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +// ChargeMobile charges the mobile device |
| 59 | +func (m *Mobile) ChargeMobile(minutes int) { |
| 60 | + m.LastUsage = time.Now() |
| 61 | + m.Battery += minutes |
| 62 | + if m.Battery > 100 { |
| 63 | + m.Battery = 100 |
| 64 | + } |
| 65 | + fmt.Printf("Charging %s %s for %d minutes.\n", m.Brand, m.Model, minutes) |
| 66 | +} |
| 67 | + |
| 68 | +func main() { |
| 69 | + // Create a new mobile device |
| 70 | + myMobile := Mobile{ |
| 71 | + Brand: "Apple", |
| 72 | + Model: "iPhone X", |
| 73 | + IsOn: false, |
| 74 | + Battery: 50, |
| 75 | + } |
| 76 | + |
| 77 | + // Turn on the mobile device |
| 78 | + myMobile.TurnOn() |
| 79 | + |
| 80 | + // Simulate using the mobile device |
| 81 | + myMobile.UseMobile(60) |
| 82 | + |
| 83 | + // Charge the mobile device |
| 84 | + myMobile.ChargeMobile(30) |
| 85 | + |
| 86 | + // Simulate using the mobile device again |
| 87 | + myMobile.UseMobile(120) |
| 88 | + |
| 89 | + // Turn off the mobile device |
| 90 | + myMobile.TurnOff() |
| 91 | +} |
0 commit comments