Advertisement
den4ik2003

Untitled

Mar 7th, 2024
693
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.51 KB | None | 0 0
  1. class ComplexNumber(private val re: Double, private val im: Double) {
  2.   def +(otherNumber: ComplexNumber) = new ComplexNumber(re + otherNumber.re, im + otherNumber.im)
  3.  
  4.   def -(otherNumber: ComplexNumber) = new ComplexNumber(re - otherNumber.re, im - otherNumber.im)
  5.  
  6.   def *(otherNumber: ComplexNumber): ComplexNumber = {
  7.     new ComplexNumber(re * otherNumber.re - im * otherNumber.im, im * otherNumber.re + re * otherNumber.im)
  8.   }
  9.  
  10.   def printComplex(): Unit = {
  11.     println(s"${re} + ${im}i")
  12.   }
  13. }
  14.  
  15. object ComplexNumbersCalculator extends App {
  16.   private def createComplexNumberFromConsole() = {
  17.     println("Enter real part:")
  18.     val re = scala.io.StdIn.readDouble()
  19.  
  20.     println("Enter imaginary part:")
  21.     val im = scala.io.StdIn.readDouble()
  22.  
  23.     new ComplexNumber(re, im)
  24.   }
  25.  
  26.   private var continue = true
  27.   while (continue) {
  28.     val num1: ComplexNumber = createComplexNumberFromConsole()
  29.     val num2: ComplexNumber = createComplexNumberFromConsole()
  30.  
  31.     println("Choose operation ['+', '-', '*']:")
  32.     val operation = scala.io.StdIn.readChar()
  33.     if (operation == '+') {
  34.       (num1 + num2).printComplex()
  35.     } else if (operation == '-') {
  36.       (num1 - num2).printComplex()
  37.     } else if (operation == '*') {
  38.       (num1 * num2).printComplex()
  39.     } else {
  40.       println("Unknown operation!")
  41.     }
  42.  
  43.     println("You want continue? (Y/n)")
  44.     val continueRequest = scala.io.StdIn.readChar()
  45.     continue = if (continueRequest == 'Y') true else false
  46.   }
  47.   println("Bye bye!")
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement