Scala, Java 50 programming questions

Keywords: Java Scala Hadoop

⚠️ The correctness of the solution is not guaranteed!

1. There are a pair of rabbits. From the third month after birth, a pair of rabbits are born every month. The rabbits grow to another pair of rabbits every month after the third month. If none of the rabbits dies, what is the total number of rabbits per month?

def main(args: Array[String]): Unit = {
    var x = 30
    val arr = new Array[Int](x)
    arr(0) = 1 ; arr(1) = 1
    for(i <- 2 to x-1){
      arr(i) = arr(i-1) + arr(i-2)
      println(s"No. ${i+1} The number of rabbits per month is: ${arr(i)} only")
    }
}
Output:
Number of rabbits in March: 2
 Number of rabbits in April: 3
 The number of rabbits in May is: 5
 Number of rabbits in June: 8
 Number of rabbits in July: 13
 The number of rabbits in August was 21.
Number of rabbits in September: 34
 Number of rabbits in October: 55
 Number of rabbits in November: 89
 Number of rabbits in December: 144
 The number of rabbits in March 1 was 233.
The number of rabbits in April was 377.
Number of rabbits in 15th month: 610
 The number of rabbits in June was 987.
Number of rabbits in July: 1597
 The number of rabbits in August was 2584.
The number of rabbits in December 19 was 4181
 The number of rabbits in the 20th month was 6765
 Number of rabbits in November: 10 946
 The number of rabbits in February was 17 711.
The number of rabbits in March 2 was 28 657
 The number of rabbits in April was 46,368
 The number of rabbits in May 2 was 75,025.
Number of rabbits in June: 121393
 Number of rabbits in July: 196418
 The number of rabbits in August was 317811
 The number of rabbits in September was 514 229
 The number of rabbits in October was 83,2040

2. Determine how many prime numbers are between 101-200 and output all prime numbers. A prime number is also called a prime number, which means that there is no integer divisible by it except 1 and itself. That is, a prime number has only two factors.

def main(args: Array[String]): Unit = {
    for (i <- 101 to 200) {
      var flag = true
      for (j <- 2 to 9 if flag != false){
        if (i % j == 0) flag = false
      }
      if (flag) println(i)
    }
}
Output:
101
103
107
109
113
121
127
131
137
139
143
149
151
157
163
167
169
173
179
181
187
191
193
197
199

3. Print out all the "number of daffodils". The so-called "number of daffodils" refers to a three-digit number with each digit cube equal to the number itself. For example, 153 is a "number of daffodils" because 153=1 of cubic + 5 of cubic + 3 of cubic. In those days, all of these questions were answered online, but now things have changed, they won't and won't.

def main(args: Array[String]): Unit = {
    for (i <- 100 to 1000) {
        var a = i % 10; //123 % 10
        var b = i / 10 % 10; //12 % 10;
        var c = i / 10 / 10 % 10; //1 % 10
        if (Math.pow(a,3) + Math.pow(b,3) + Math.pow(c,3) == i) println(i)
    }
}
Output:
153
370
371
407

4. Decomposition a positive integer into prime factors. For example, enter 90 and print out 90=233*5.

(1) If the prime number is exactly equal to n, then the process of decomposing the prime factor has ended and can be printed out.
(2) If n<>k, but n is divisible by k, print out the value of K and divide n by the quotient of K. As a new positive integer, repeat the first step.
(3) If n is not divisible by k, repeat the first step using k+1 as the value of K.

def main(args: Array[String]): Unit = {
  var n = 90
  var k = 2
  print(s"${n}=")
  while (n != k) {
    if (n % k == 0) {
      print(s"${k}*")
      n = n / k
    } else {
      k = k + 1
    }
  }
  print(k)
}
Output:
90=2*3*3*5

5. Use nesting of conditional operators to complete this problem: students with academic achievement >=90 points are represented by A, between 60-89 points by B, and below 60 points by C.

def main(args: Array[String]): Unit = {
  var score = 100
  if (score >= 90) {
    println("A")
  } else {
    if(score >= 60){
      println("B")
    } else {
      println("C")
    }
  }
}
Output:
A

6. Enter two positive integers m and n to find the maximum and minimum common multiples.

def main(args: Array[String]): Unit = {
  val x = 42
  val y = 36
  var sta: mutable.Stack[Int] = new mutable.Stack[Int]
  for (i <- 1 to x; if (x % i == 0 & y % i == 0)) sta.push(i)
  var i: Int = sta.pop()
  println(s"The maximum common divisor is: $i")
  println(s"The lowest common multiple is: ${x * y / i}")
}
Output:
The maximum common divisor is:6
 Minimum common multiple: 252

7. Enter a line of characters to count the number of letters, spaces, numbers and other characters in English.

def main(args: Array[String]): Unit = {
    var content: Array[Char] = ((new Scanner(System.in)).nextLine()).toCharArray
    var zm, kg, sz, qt = 0
    for (elem <- content) {
        if ('a' <= elem && elem <= 'z' || 'A' <= elem && elem <= 'Z')  zm += 1
        else if (' ' == elem )  kg += 1
        else if ('1' <= elem && elem <= '9')  sz += 1 else qt += 1
    }
    println(s"The letters have $zm individual\n Spaces have $kg individual\n Numbers have $sz individual\n Other characters are $qt individual")
}
Input:
sghye356hf7456767632re;'wetet.';'wetye'tyye;'rw'wetry etew er
 Output:
There are 36 letters
 There are two spaces
 There are 13 numbers
 10 other characters

8. Value s=a+a a+a a a+a a a a a a+a a...a, where a is a number. For example, 2+22+222+2222+22222 (when there are five numbers added), several numbers added together have keyboard control.

def main(args: Array[String]): Unit = {
  val x = 6
  var sum = 0
  var array: Array[String] = new Array[String](x)
  var str = String.valueOf(x)
  for (i <- 0 to x-1){
    array(i) = s"${x}" * (i+1)
  }
  for (elem <- array) {
    sum += Integer.valueOf(elem)
  }
  println(sum)
}
Output:
740736

9. If a number is exactly equal to the sum of its factors, this number is called the "perfect number". For example, 6=1+2+3.Programming finds all completions within 1000

def main(args: Array[String]): Unit = {
    var sum = 0
    for (x <- 1 to 1000) {
        for (y <- 1 to x) {
            if (x % y == 0) sum += y
        }
        if (sum - x == x) println(x)
        sum = 0
    }	
}
Output:
6
28
496

10. A ball falls freely from a height of 100 meters and bounces back half of its original height after each fall. How many meters did it pass when it fell again for the tenth time? How high is the 10th bounce?

def main(args: Array[String]): Unit = {
    var sum, high: Double = 100
    for (x <- 2 to 10) {
        high = high / 2
        sum += high * 2
    }
    println(s"Altogether ${sum} rice")
    println(s"No. ${10} The height of the second rebound is mostly ${high}")
}
Output:
A total of 299.609375 rice
 The height of the 10th bounce is more than zero.1953125

11. With 1, 2, 3, 4 digits, how many different three digits can they make up without repeating numbers? How many are they?

def main(args: Array[String]): Unit = {
    var arr = Array(1, 2, 3, 4)
    var count = 0
    for (x <- 1 to 4;
         y <- 1 to 4;
         z <- 1 to 4) {
        if (x!=y && x!=z && y!=z){
            count += 1
            println(s"$x$y$z")
        }
    }
    println(s"Total $count species")
}
Output:
123
124
132
134
142
143
213
214
231
234
241
243
312
314
321
324
341
342
412
413
421
423
431
432
 There are 24 types

12. Bonuses paid by enterprises shall be based on profits. When profit (I) is less than or equal to 100,000 yuan, the bonus may be increased by 10%; When the profit is higher than 100,000 yuan and less than 200,000 yuan, the part less than 100,000 yuan is deducted by 10%, and the part higher than 100,000 yuan is deducted by 7.5%; Between 200,000 and 400,000 yuan, the portion above 200,000 yuan can be deducted by 5%; If the amount between 400,000 and 600,000 yuan is higher than 400,000 yuan, 3% may be deducted. Between 600,000 and 1,000,000 yuan, the part over 600,000 yuan can be deducted by 1.5%, while the part over 1,000,000 yuan is deducted by 1%. Should the total bonus be paid by entering profit I for the month from the keyboard?

def main(args: Array[String]): Unit = {
    var profit: Double = 123456
    var bonus: Double = 0.00

    if (profit <= 100000) {
        bonus = profit * 0.1
    } else if (profit < 200000) {
        bonus = 10000 + (profit - 100000) * 0.075
    } else if (profit < 400000) {
        bonus = 17500 + (profit - 200000) * 0.05
    } else if (profit < 600000) {
        bonus = 27500 + (profit - 400000) * 0.03
    } else if (profit < 1000000) {
        bonus = 33500 + (profit - 600000) * 0.015
    } else {
        bonus = 36500 + (profit - 1000000) * 0.01
    }
    println(s"Pay bonus for $bonus ¥")
}
Output:
Bonus payment is 11759.2 ¥

13. An integer, which is a complete square number after adding 100, and 168 is a complete square number. What is the number, please?

def main(args: Array[String]): Unit = {
    var x = 0
    var flag = true
    while (flag) {
        x += 1
        if (math.sqrt(x + 100) % 1 == 0 && math.sqrt(x + 268) % 1 == 0) flag = false
    }
    println(s"This number is: $x")
}
Output:
This number is: 21

14. Enter the date of a month and a year to determine the day of the year?

def main(args: Array[String]): Unit = {
    var content = new Scanner(System.in)
    var year = content.nextInt()
    var month = content.nextInt()
    var days = content.nextInt()
    var Feb = 28
    if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) Feb = 29
    //    days = (month / 2: Int) * 31 + (month / 2 - 1: Int) * 30 + days + Feb
    var arr = Array(0,31,Feb,31,30,31,30,31,31,30,31,30)
    for (i <- 0 to month-1){
        days += arr(i)
    }
    println(s"This is the day of the year $days Day!")
}
Input:
2021 12 6
 Output:
This is the 340th day of the year!

15. Enter three integers x,y,z, and output them from small to large.

def main(args: Array[String]): Unit = {
    println("Please enter three numbers x,y,z : ")
    var sc = new Scanner(System.in)
    var map = SortedMap(sc.nextInt() -> "x", sc.nextInt() -> "y", sc.nextInt() -> "z")
    for (elem <- map) {
        print(elem._2 + " ")
    }
}
Input:
Please enter three numbers x,y,z : 
5 3 7
 Output:
y x z 

16. Output 9*9 tricks.

def main(args: Array[String]): Unit = {
    for (i <- 1 to 9; j <- 1 to i) {
        print(s"${i}*${j}=${i * j}\t")
        if (i == j) println()
    }
}
Output:
1*1=1	
2*1=2	2*2=4	
3*1=3	3*2=6	3*3=9	
4*1=4	4*2=8	4*3=12	4*4=16	
5*1=5	5*2=10	5*3=15	5*4=20	5*5=25	
6*1=6	6*2=12	6*3=18	6*4=24	6*5=30	6*6=36	
7*1=7	7*2=14	7*3=21	7*4=28	7*5=35	7*6=42	7*7=49	
8*1=8	8*2=16	8*3=24	8*4=32	8*5=40	8*6=48	8*7=56	8*8=64	
9*1=9	9*2=18	9*3=27	9*4=36	9*5=45	9*6=54	9*7=63	9*8=72	9*9=81

17. The monkey eats peaches: The monkey picks several peaches on the first day, eats half of them immediately, is not addicted to it, eats half of the remaining peaches the next morning, and eats one more. Every morning afterwards, I ate half and one half of the rest of the previous day. When I wanted to eat again the morning of the 10th day, I saw there was only one peach left. Ask how many you picked on the first day.

def main(args: Array[String]): Unit = {
    var count = 1
    var days = 10
    for (i <- 1 to days - 1) {
        count = 2 * (count + 1)
    }
    println(s"Picked on the first day ${count} individual")
}
Output:
A total of 1534 were picked on the first day

18. Two table tennis teams compete, each with three players. Team A has three players a, B and c and team B has three players x, y and Z. The list of matches has been drawn. Someone asked the team for the list of matches. A said he didn't compare with x, c said he didn't compare with x,z. Please program to find out the list of three players.

def main(args: Array[String]): Unit = {
    for (a: Char <- 'x' to 'z') {
        for (b: Char <- 'x' to 'z') {
            for (c: Char <- 'x' to 'z') {
                if (a != 'x' && c != 'x' && c != 'z' && a != b && a != c && b != c) {
                    println(s" a -> ${a}")
                    println(s" b -> ${b}")
                    println(s" c -> ${c}")
                }
            }
        }
    }
}
Output:
 a -> z
 b -> x
 c -> y

19. Print out the following pattern (diamond)

    *
   ***
 ******
********
 ******
   ***
    *
def main(args: Array[String]): Unit = {
    var num = 4
    for (i <- 1 to num) {
        for (x <- 1 to num - i) print(" ")
        for (y <- 1 to 2 * i - 1) print("*")
        println()
    }
    for (i <- 1 to num - 1 reverse){
        for (x <- 1 to num - i) print(" ")
        for (y <- 1 to 2 * i - 1) print("*")
        println()
    }
}
Output:
   *
  ***
 *****
*******
 *****
  ***
   *

20. There is a fraction sequence: 2/1, 3/2, 5/3, 8/5, 13/8, 21/13... sum the first 20 items of this sequence.

def main(args: Array[String]): Unit = {
    var num = 20
    var fz:Double = 2
    var fm:Double = 1
    var tmp, sum:Double = 0
    for (i <- 1 to num) {
        sum =  sum + fz / fm
        tmp = fz
        fz = fz + fm
        fm = tmp
    }
    println(sum)
}
Output:
32.66026079864164

21, Seek 1+2!+ 3!+...+ 20! And

def main(args: Array[String]): Unit = {
    var num = 20
    var sum: Long = 0
    var tmp: Long = 1
    for (j <- 1 to num) {
        tmp = tmp * j
        sum += tmp
    }
    println(sum)
}
Output:
2561327494111820313

22. Use recursive method to find 5!.

def main(args: Array[String]): Unit = {
    def f(n: Int): Int = {
        if (n == 1) return 1
        return n*f(n-1)
    }
    println(f(5))
}
Output:
120

23. Five people sat together and asked how old is the fifth person? He said he was two years older than the fourth person. When asked about the age of the fourth person, he said he was two years older than the third person. Ask the third person, who is two years older than the second person. Ask the second person and say he is two years older than the first person. Finally, I asked the first person, who said he was 10 years old. How old is the fifth person?

def main(args: Array[String]): Unit = {
  def f(age: Int):Int= if(age == 1) return 10 else return f(age-1) + 2
  print(s"Fifth person ${f(5)} year")
}
Output:
Fifth person, 18 years old

24. To give a positive integer with no more than 5 digits, the following requirements are required: 1. Seek how many digits it is, and 2. Print out each digit in reverse order.

def main(args: Array[String]): Unit = {
    var sc = (new Scanner(System.in)).next()
    print(s"This is a ${sc.length} digit \n The reverse order is:")
    for (i <- 0 to sc.length - 1 reverse) print(sc(i))
}
Input:
47847
 Output:
This is a five digit number 
The reverse order is: 74874

25. A 5-digit number to determine whether it is palindrome. That is, 12321 is the palindrome number, with 10 digits identical to 10,000 digits.

def main(args: Array[String]): Unit = {
    var sc = (new Scanner(System.in)).next()
    for (i <- 0 to sc.length - 1) {
        if (sc(0) != sc(sc.length - 1 - i)) {
            print("Not palindrome")
            return 0
        } else {
            print("Is palindrome")
            return 0
        }
    }
}
Input:
asdfdsa
 Output:
Is palindrome

26. Enter the first letter of the day of the week to judge which day of the week it is. If the first letter is the same, continue to judge the second letter.

def main(args: Array[String]): Unit = {
    var week = Map("m" -> "Monday", "tu" -> "Tuesday", "w" -> "Wednesday", "th" -> "Thursday", "f" -> "Friday", "sa" -> "Saturday", "su" -> "Sunday")
    var sc = (new Scanner(System.in)).next().toLowerCase()
    print(week.getOrElse(sc, "Input error"))
}
Input:
Tu
 Output:
Tuesday

27. Find prime numbers within 100

def main(args: Array[String]): Unit = {
    println("1\n2")
    for (i <- 2 to 100) {
        var flag = true
        for (j <- 2 to i) {
            if (i % j == 0) flag = false
            if (j == i - 1 && flag) println(i);
        }
    }
}
Output:
1
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97

28. Sort 10 numbers

def main(args: Array[String]): Unit = {
    var arr = Array(23, 62, 74, 235, 58, 23, 78, 34, 34, 73)
    var tmp = 0
    for (i <- 0 until arr.length - 1; j <- 0 until arr.length - 1 - i) {
        if (arr(j) > arr(j + 1)) {
            tmp = arr(j)
            arr(j) = arr(j + 1)
            arr(j + 1) = tmp
        }
    }
    println(arr.toList)
}
Output:
List(23, 23, 34, 34, 58, 62, 73, 74, 78, 235)

29. Sum the diagonal elements of a 3*3 matrix

def main(args: Array[String]): Unit = {
    var arr: Array[Array[Int]] = Array.ofDim(3,3)
    for (i <- 0 to 2) {
        for ( j <- 0 to 2) {
            arr(i)(j) = j;
        }
    }
    for (i <- 0 to 2) {
        for ( j <- 0 to 2) {
            print(" " + arr(i)(j));
        }
        println();
    }
    var sum = 0
    for (i <- 0 to 2; j <- 0 to 2) {
        if (i == j || i == 2 - j) {
            sum += arr(i)(j)
        }
    }
    println(sum)
}
Output:
 0 1 2
 0 1 2
 0 1 2
5

30. There is an array already sorted. Now enter a number and ask to insert it into the array as usual.

def main(args: Array[String]): Unit = {
    var num = 53
    var arr = ArrayBuffer[Int](23, 23, 34, 34, 58, 62, 73, 74, 78, 235)
    arr += 0
    var tmp = 0
    Breaks.breakable(
        for (i <- 0 to arr.size-1 reverse) {
            arr(i) = arr(i-1)
            if (num > arr(i)){
                arr(i) = num
                Breaks.break()
            }
        }
    )
    println(arr.toList)
}
Output:
List(23, 23, 34, 34, 53, 58, 62, 73, 74, 78, 235)

31. Output an array in reverse order.

def main(args: Array[String]): Unit = {
    var arr = Array[Int](23, 23, 34, 34, 58, 62, 73, 74, 78, 235)
    for (i <- 0 to arr.size -1 reverse) {
        print("\t" + arr(i))
    }
}
output;
235	78	74	73	62	58	34	34	23	23

32. Take an integer a starting at the right 4-7 digits.

def main(args: Array[String]): Unit = {
    var sc = (new Scanner(System.in)).next()
    print(sc.substring(sc.length-7,sc.length-3))
}
Input:
987345635
 Output:
7345

33. Print out Yang Hui triangle (requires 10 lines to be printed as follows)

      1
     1 1
    1 2 1
   1 3 3 1
  1 4 6 4 1
1 5 10 10 5 1
def main(args: Array[String]): Unit = {
    var num = 6
    var arr = Array.ofDim[Int](num + 1, num + 1)
    for (i <- 1 to num) {
        for (j <- 1 to i) {
            if (j == 0 || j == i) arr(i)(j) = 1 else arr(i)(j) = arr(i - 1)(j) + arr(i - 1)(j - 1)
        }
    }
    for (x <- 1 to num) {
        print("\t"*(num-x))
        for (y <- 1 to num) {
            if (arr(x)(y) != 0) print(s"\t${arr(x)(y)}\t")
        }
        println()
    }
}
Output:
						1	
					1		1	
				1		2		1	
			1		3		3		1	
		1		4		6		4		1	
	1		5		10		10		5		1	

34. Enter three numbers a,b,c and output them in size order.

def main(args: Array[String]): Unit = {
    println("Please enter three numbers a,b,c:")
    var sc = new Scanner(System.in)
    var map = SortedMap(sc.nextInt() -> "a", sc.nextInt() -> "b", sc.nextInt() -> "c")
    map.foreach(elem => print(elem._2 + " "))
}
Input:
Please enter three numbers a,b,c:
535 745 345
 output
c a b 

35. Input array, maximum exchange with first element, minimum exchange with last element, output array.

def main(args: Array[String]): Unit = {
    var arr = Array(23, 62, 74, 235, 58, 68, 78, 36, 34, 73)

    var tmp = arr.max
    arr(arr.indexOf(arr.max)) = arr(0)
    arr(0) = tmp

    tmp = arr.min
    arr(arr.indexOf(arr.min)) = arr(arr.size - 1)
    arr(arr.size - 1) = tmp

    println(arr.toList)
}
Output:
List(235, 62, 74, 73, 58, 68, 78, 36, 34, 23)

36. Have n integers so that the first number moves backwards m places, and the last m becomes the first m

def main(args: Array[String]): Unit = {
    var arr = ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9)
    var times = 3
    var num = 0
    for (i <- 0 to times - 1) {
        num = arr(0)
        for (j <- 0 to arr.size - 2) arr(j) = arr(j + 1)
        arr(arr.size - 1) = num
    }
    println(arr)
}
Output:
ArrayBuffer(4, 5, 6, 7, 8, 9, 1, 2, 3)

37. There are n individuals in a circle, numbered in sequence. From the first person to report (from 1 to 3), anyone who reports to 3 quits the circle and asks who left behind the original number.

def main(args: Array[String]): Unit = {
    var arr = ArrayBuffer[Int]()
    for (i <- 0 until 20) {
        arr += i + 1
    }

    /**
   *Implementation Method
   * @param array  Incoming Array
   * @param start  Position of first start
   * @return
   */
    def f(array: ArrayBuffer[Int], start: Int): ArrayBuffer[Int] = {
        var tmp = ArrayBuffer[Int]()
        // Get the number called 3 in this round
        for (i <- 0 to array.size - 1) if ((i + start) % 3 == 0) tmp += array(i)
        // Next round, number of first person calls
        var nextStart = (array.size - 1 - array.indexOf(tmp.last)) + 1
        // Remove the number called 3 in this round
        for (elem <- tmp) array -= elem
        // Judging Residual and Recursive
        if (arr.size > 2) f(array, nextStart) else return array
    }

    arr = f(arr, 1)
    arr.foreach(println)

}
output
13
20

38. Write a function to find the length of a string. Enter a string in the main function and output its length.

def main(args: Array[String]): Unit = {

    var str = (new Scanner(System.in)).next()
    def f(str: String):Int = return str.length
    print(s"The length of the string is: ${f(str)}")
}
Input:
ykhghgewtry
 Output:
The length of the string is: 11

39. Write a function that evaluates 1/2+1/4+...+1/n when n is an even number of inputs. When n is an odd number, call function 1/1+1/3+...+1/n (using pointer function)

def main(args: Array[String]): Unit = {

    var num = (new Scanner(System.in)).nextInt()

    def f(num: Int): Double = {
        var sum: Double = 0.00
        if (num % 2 == 0) {
            for (i <- 2 to num) if (i % 2 == 0) sum += (1 / i.toDouble)
        } else {
            for (i <- 1 to num) if (i % 2 != 0) sum += (1 / i.toDouble)
        }
        return sum
    }
    var res = f(num)
    println(s"The results are: $res ")
}
Input:
6
 Output:
The result is:0.9166666666666666 

40. String sorting.

def main(args: Array[String]): Unit = {
    var charArr = new Scanner(System.in).next().toCharArray
    var tmp = ' '
    for (i <- 0 until  charArr.size - 1; j <- 0 until  charArr.size - 1 - i) {
        if (charArr(j) > charArr(j + 1)) {
            tmp = charArr(j)
            charArr(j) = charArr(j+1)
            charArr(j+1) = tmp
        }
    }
    println(charArr.toList)
}
Input:
weyrhdf
 Output:
List(d, e, f, h, r, w, y)

41. There are a bunch of peaches on the beach and five monkeys to share. The first monkey divided the stack of peach credentials into five parts, one more. The monkey threw the other one into the sea and took one. The second monkey evenly divided the remaining peaches into five and one more. It also threw the other one into the sea and took one. The third, fourth and fifth monkeys all did this. Ask how many peaches were there on the beach at least?

public static void main(String[] args) {
    System.out.println(s(10));

}
static int s(int i){
    int u=i;
    for(int x=0;x<5;x++){
        if(i%5!=1)
            return s(u+1);
        i=(i-1)/5*4;
    }
    return u;
}
Output:
3121

42, 809*?= 800*??+ 9*??+ 1 of which?? Two digits, 8*?? The result is two digits, 9*?? The result is 3 digits. Ask?? Two digits for, and 809*?? The result after.

def main(args: Array[String]): Unit = {
    for (i <- 10 to 13) {
        if (8 * i < 100
            && 9 * i >= 100
            && 9 * i < 1000
            && 809 * i == 800 * i + 9 * i + 1) {
            print(s"The number is ${i}, 809*??=${809 * i}")
        }
        else {
            print("No solution!")
        }
    }
}
Output:
No solution! No solution! No solution!

43. Find the odd number that 0-7 can make up.

def main(args: Array[String]): Unit = {

    // There are four types of odd numbers of one digit: 1, 3, 5, 7
    var count = 4

    def f(num: Int): Int = {
        var res = 1
        for (i <- 1 to num) {
            res *= i
        }
        return res
    }

    for (i <- 2 to 8) {
        count += ((f(7) / f(8 - i) - f(6) / f(8 - i)) * 4)
    }
    println(s"0—7 The number of odd numbers that can be composed is: $count ")
}
Output:
0—7 The odd number of components is 46972 

44. An even number can always be expressed as the sum of two prime numbers.

def main(args: Array[String]): Unit = {
    var num = new Scanner(System.in).nextInt()
    var arr = new ArrayBuffer[Int]
    for (i <- 2 to num) {
        var flag = true
        for (j <- 2 to i) {
            if (i % j == 0) flag = false
            if (j == i - 1 && flag) {
                arr += i
            }
        }
    }
    for (elem1 <- arr; elem2 <- arr) {
        if (elem1 + elem2 == num) {
            println(s"${num} The number of times can be expressed as: ${elem1} + ${elem2} ")
        }
    }
}
Input:
78
 Output:
78 The number of times can be expressed as:5 + 73 
78 The number of times can be expressed as:7 + 71 
78 The number of times can be expressed as:11 + 67 
78 The number of times can be expressed as:17 + 61 
78 The number of times can be expressed as:19 + 59 
78 Number of times can be expressed as:31 + 47 
78 Number of times can be expressed as:37 + 41 
78 Number of times can be expressed as: 41 + 37 
78 Number of times can be expressed as:47 + 31 
78 Number of times can be expressed as:59 + 19 
78 The number of times can be expressed as:61 + 17 
78 Number of times can be expressed as: 67 + 11 
78 Number of times can be expressed as: 71 + 7 
78 Number of times can be expressed as:73 + 5 

45. Judging that a prime number can be divided by several nine integers

def main(args: Array[String]): Unit = {
    var num = new Scanner(System.in).nextInt()
    var res:Int = num / 9
    print(s"This number can be ${res} 9 divisions")
}
Input:
74
 Output:
This number can be divided by eight nine integers

46. Two String Connectors

def main(args: Array[String]): Unit = {
    var str = new Scanner(System.in)
    print(s"Connected as: ${str.next() + str.next()}")
}
Input:
sef etyr
 Output:
Connected as: sefetyr

47. Read the integer values of seven numbers (1-50). For each value read, the program prints out the number of irons for that value.

def main(args: Array[String]): Unit = {
    for (i <- 1 to 7) {
        var num :Int= ( Math.random()*50).toInt
        println(s" ${num}  ${"*"*num}")
    }
}
Output:
 11  ***********
 9  *********
 28  ****************************
 24  ************************
 28  ****************************
 5  *****
 15  ***************

48. A company uses public telephone to transfer data. The data is a four-digit integer and is encrypted during the transfer process. The encryption rules are as follows: add 5 to each digit, then replace the number with the remainder divided by 10, and then exchange the first and fourth digits, the second and third digits.

def main(args: Array[String]): Unit = {
    println("Enter the data you want to pass:")
    var sc = new Scanner(System.in).next().toArray
    sc.map( _.toInt.+(5).%(10))
    .reverse
    .foreach(print)
}
Input:
Enter the data you want to pass:
1234
 Output:
7654

49. Calculate the number of occurrences of neutron strings in a string

def main(args: Array[String]): Unit = {
    var sc = new Scanner(System.in)
    var str, sub = sc.next()
    var count = 0
    for (i <- 0 to str.length - sub.length) {
        if (sub.equals(str.substring(i, sub.length + i))) count += 1
    }
    println(s"The number of occurrences of substrings is: $count ")
}
Input:
rtyhgadsrty rt
 Output:
The number of occurrences of substrings is:2 

50. There are five students, each student has three courses'results. Enter the above data from the keyboard (including student number, name, three courses' results), calculate the average results, and store the original data and calculated average scores in the disk file "stud".

def main(args: Array[String]): Unit = {

    var arr = new ArrayBuffer[Array[String]]
    var average_scores = new Array[Int](3)

    var sc = new Scanner(System.in)
    val stream = new FileOutputStream(new File("stud.txt"))

    println("Please enter a number, name and three subjects:")

    // Store student information
    for (i <- 1 to 5) {
        var content = sc.nextLine()
        stream.write((content + "\n").getBytes)
        arr += content.split(" ")
    }
    // Calculate Average Score
    for (i <- 2 to arr(0).size - 1) {
        var souces = 0
        for (j <- 0 to arr.size - 1) souces += Integer.valueOf(arr(j)(i))
        average_scores(i - 2) = souces / 5
    }
    for (i <- 0 to average_scores.size - 1) stream.write((average_scores(i) + "\t").toString.getBytes())
    stream.close()
}
Input:
01 Zhang San 45 84 63
02 Li Si 52 34 85
03 Wang Wu74 75 64
04 Zhao Liu 74 58 85
05 A7 85 45 75
 Output: stud.txt
01 Zhang San 45 84 63
02 Li Si 52 34 85
03 Wang Wu74 75 64
04 Zhao Liu 74 58 85
05 A7 85 45 75
66	59	74	

 

❤️ END ❤️

Posted by GreyFilm on Mon, 06 Dec 2021 09:13:55 -0800