Related java assignments on Touge: java common classes

“”"
original author: jacky Li
Email : [email protected]
Last edited: 2022.11.9
“”"

Table of contents

Related java assignments on Touge: java common classes

Level 1: String class

mission details

related information

Programming requirements

Test instruction

Level 2: StringBuffer class

mission details

related information

Programming requirements

Test instruction

Level 3: Math class

mission details

related information

Programming requirements

Test instruction

Level 4: Random class

mission details

related information

Programming requirements

Test instruction

Level 5: Knowledge review

mission details

related information

Programming requirements

Test instruction


1265b3318ce64daab33ff7d7a5a1b6c5.jpeg

 

 

Related java assignments on Touge: java common classes

Level 1: String class

mission details

Task for this level: Be familiar with the basic use of String class

related information

1 Overview

A string is a string of data (character sequence) composed of multiple characters. A string can be regarded as a character array.

In actual development, string operations are the most common operations, bar none. Java does not have a built-in string type, so a String class is provided in the Java class library for us to use. The String class represents strings.

Strings are often used in applications. The so-called string refers to a series of characters. It is connected by many single characters, such as an English word composed of multiple English letters. The string can contain any characters, and these characters must be enclosed in a pair of double quotes "", such as "abc". Two classes, String and StringBuffer, are defined in Java to encapsulate strings and provide a series of methods for operating strings. They are all located in the java.lang package, so they can be used directly without importing the package.

2. Characteristics of String class

  • A string is a constant and its value cannot be changed after it is created.

  • All string literals (such as "abc") in Java programs are implemented as instances of this class.

  • If strings are added by variables, space is opened first and then spliced.

  • If strings are added by constants, they are added first and then found in the constant pool. If there is one, it is returned directly. Otherwise, it is created.

     
    1. package cn.itcast_02;
    2. /*
    3. * 字符串的特点:一旦被赋值,就不能改变。
    4. */
    5. public class StringDemo {
    6. public static void main(String[] args) {
    7. String s = "hello";
    8. s += "world";
    9. System.out.println("s:" + s); // helloworld
    10. }
    11. }

String in memory 2

String s1 = new String(“hello”);What is the difference between and String s2 = “hello”;?

The former creates 2 or 1 objects, the latter creates 1 or 0 objects.

 
  1. String s1 = new String(“hello”);
  2. String s2 = “hello”;
  3. s1 == s2; // false
  4. s1.equals(s2); // true
  5.  
  6. String s3 = “hello”; String s4 = “world”; String s5 = “helloworld”;
  7.  
  8. S5== s3 + s4 ; //fale
  9. s5 == “hello” + ”world”; //true

If strings are added by variables, space is opened first and then concatenated.

If strings are added by constants, they are added first, and then found in the string constant pool. If there is one, it is returned directly, otherwise it is created.

3. Common operating methods

 

3.1 Construction method

method illustrate
String() Create an empty string
String(byte[]) Create an object based on the specified byte array
String(byte[],int,int) Create an object from a portion of a byte array
String(char[]) Create an object based on the specified character array
String(char[],int,int) Create an object from part of a character array
String(String) Create an object based on the specified string content
String(byte[] bytes, Charset charset) Constructs a string object using the specified encoding

3.2 Judgment function

method illustrate
equals() Compares the contents of strings for equality, case-sensitive
equalsIgnoreCase() Compares the contents of strings for equality, ignoring case
contains(String str) Determine whether a large string contains a small string
startsWith() Determine whether a string begins with a certain string
endsWith() Determine whether a string ends with a certain string
isEmpty() Determine whether the string is empty

3.3 Get function

method illustrate
length() Get string length
charAt(int index) Get the character at the specified position
indexOf(int ch) index of first occurrence of character
indexOf(String str) Index of first occurrence of string
indexOf(int ch,int fromIndex) Index of the first occurrence of the character after the specified position
indexOf(String str,int from) Index of the first occurrence of the string after the specified position
lastIndexOf() Index of last occurrence of string
subString(int start) Intercept the string starting from the specified position
subString(int start,int end) Intercept the string, including the left but not the right

3.4 Conversion function

method illustrate
getBytes() Convert string to byte array
getCharArray() Convert string to character array
valueOf(char[] chs) Convert character array to string
valueOf(int i) Convert int type data to string
toLowerCase() Convert string to lowercase
toUpperCase() Convert string to uppercase
concat(String str) 字符串拼接

3.5 其他功能

方法 说明
replace(char old,char new) 替换字符
replace(String old,String new) 替换字符串
trim() 去掉字符串两端空格
compareTo() 按字典顺序比较字符串
compareToIngnoreCase() 按字典顺序比较字符串,忽略大小写
format() 格式化字符串

编程要求

根据提示,在右侧编辑器补充代码,完成以下任务:

1.输出原字符串

2.求出字符串长度

3.字符串转换成相应的大/小写

4.截取指定位置的字符串(3-7)

5.字符串相加

测试说明

平台会对你编写的代码进行测试:

测试输入:heLLo,WOrld,NICE 预期输出: 平均值:44.0 最大值:91

测试输入:511511222100; 预期输出: 原字符串为:heLLo,WOrld,NICE 字符串长度为:16 转换成大写字符串:HELLO,WORLD,NICE 转换成小写字符串:hello,world,nice 第3-7的字符串内容为:Lo,W 字符串相加后:heLLo,WOrld,NICE end


开始你的任务吧,祝你成功!

 

package step1;

import java.util.Scanner;

public class StringLearning {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        String stringExample = scanner.next();
        String endStr = " end";
        // ---------------------Begin------------------------
      System.out.print("原字符串为:"+stringExample+"\n");
      System.out.print("字符串长度为:"+stringExample.length()+"\n");
      System.out.print("转换成大写字符串:"+stringExample.toUpperCase()+"\n");
      System.out.print("转换成小写字符串:"+stringExample.toLowerCase()+"\n");
    
      System.out.print("第3-7的字符串内容为:"+stringExample.substring(3,7)+"\n");
      System.out.print("字符串相加后:"+stringExample+endStr+"\n");
      
      
        // ---------------------End------------------------

    }
}

 

第2关:StringBuffer类

任务描述

本关任务:学习StringBuffer的使用,完成以下操作:

1.将stringExample转换成StringBuffer类

2.向转化后的StringBuffer增加字符串educode

3.删除5-8的字符串

4.将7-13的字符串替换成world

5.截取1-10的字符串并输出

6.反转字符串并输出

相关知识

StringBuffer概念

由于字符串是常量,因此一旦创建,其内容和长度是不可改变的。如果需要对一个字符串进行修改,则只能创建新的字符串。为了便于对字符串进行修改,在JDK中提供了一个StringBuffer类(也称字符串缓冲区)。StringBuffer类和String类最大的区别在于它的内容和长度都是可以改变的。StringBuffer类似一个字符容器,当在其中添加或删除字符时,并不会产生新的StringBuffer对象。

我们如果对字符串进行拼接操作,每次拼接,都会构建一个新的String对象,既耗时,又浪费空间。而StringBuffer就可以解决这个问题

  • StringBuffer是线程安全的可变字符序列。
  • StringBuffer和String的区别?

前者长度和内容可变,后者不可变。如果使用前者做字符串的拼接,不会浪费太多的资源。

String类表示的字符串是常量,一旦创建后,内容和长度都是无法改变的。而StringBuffer表示字符容器,其内容和长度可以随时修改。在操作字符串时,如果该字符串仅用于表示数据类型,则使用String类即可,但是如果需要对字符串中的字符进行增删操作,则使用StringBuffer类。

String类覆盖了Object类的equals()方法,而StringBuffer类没有覆盖Object类的equals()方法,具体示例如下:

String类对象可以用操作符“+”进行连接,而StringBuffer类对象之间不能,具体示例如下:

 

1. 常见操作方法

 

2. 构造方法和获取方法

 
  1. package cn.itcast_01;
  2.  
  3. /*
  4. * StringBuffer:
  5. * 线程安全的可变字符串。
  6. *
  7. * StringBuffer和String的区别?
  8. * 前者长度和内容可变,后者不可变。
  9. * 如果使用前者做字符串的拼接,不会浪费太多的资源。
  10. *
  11. * StringBuffer的构造方法:
  12. * public StringBuffer():无参构造方法
  13. * public StringBuffer(int capacity):指定容量的字符串缓冲区对象
  14. * public StringBuffer(String str):指定字符串内容的字符串缓冲区对象
  15. *
  16. * StringBuffer的获取方法:
  17. * public int capacity():返回当前容量。 理论值
  18. * public int length():返回长度(字符数)。 实际值
  19. */
  20. public class StringBufferDemo {
  21. public static void main(String[] args) {
  22. // public StringBuffer():无参构造方法
  23. StringBuffer sb = new StringBuffer();
  24. System.out.println("sb:" + sb);
  25. System.out.println("sb.capacity():" + sb.capacity());
  26. System.out.println("sb.length():" + sb.length());
  27. System.out.println("--------------------------");
  28.  
  29. // public StringBuffer(int capacity):指定容量的字符串缓冲区对象
  30. StringBuffer sb2 = new StringBuffer(50);
  31. System.out.println("sb2:" + sb2);
  32. System.out.println("sb2.capacity():" + sb2.capacity());
  33. System.out.println("sb2.length():" + sb2.length());
  34. System.out.println("--------------------------");
  35.  
  36. // public StringBuffer(String str):指定字符串内容的字符串缓冲区对象
  37. StringBuffer sb3 = new StringBuffer("hello");
  38. System.out.println("sb3:" + sb3);
  39. System.out.println("sb3.capacity():" + sb3.capacity());
  40. System.out.println("sb3.length():" + sb3.length());
  41. }
  42. }

3. 添加功能

 
  1. package cn.itcast_02;
  2.  
  3. /*
  4. * StringBuffer的添加功能:
  5. * public StringBuffer append(String str):可以把任意类型数据添加到字符串缓冲区里面,并返回字符串缓冲区本身
  6. *
  7. * public StringBuffer insert(int offset,String str):在指定位置把任意类型的数据插入到字符串缓冲区里面,并返回字符串缓冲区本身
  8. */
  9. public class StringBufferDemo {
  10. public static void main(String[] args) {
  11. // 创建字符串缓冲区对象
  12. StringBuffer sb = new StringBuffer();
  13.  
  14. // public StringBuffer append(String str)
  15. // StringBuffer sb2 = sb.append("hello");
  16. // System.out.println("sb:" + sb);
  17. // System.out.println("sb2:" + sb2);
  18. // System.out.println(sb == sb2); // true
  19.  
  20. // 一步一步的添加数据
  21. // sb.append("hello");
  22. // sb.append(true);
  23. // sb.append(12);
  24. // sb.append(34.56);
  25.  
  26. // 链式编程
  27. sb.append("hello").append(true).append(12).append(34.56);
  28. System.out.println("sb:" + sb);
  29.  
  30. // public StringBuffer insert(int offset,String
  31. // str):在指定位置把任意类型的数据插入到字符串缓冲区里面,并返回字符串缓冲区本身
  32. sb.insert(5, "world");
  33. System.out.println("sb:" + sb);
  34. }
  35. }

运行结果:

 
  1. sb:hellotrue1234.56
  2. sb:helloworldtrue1234.56

4. 删除功能

 
  1. package cn.itcast_03;
  2.  
  3. /*
  4. * StringBuffer的删除功能
  5. * public StringBuffer deleteCharAt(int index):删除指定位置的字符,并返回本身
  6. * public StringBuffer delete(int start,int end):删除从指定位置开始指定位置结束的内容,并返回本身
  7. */
  8. public class StringBufferDemo {
  9. public static void main(String[] args) {
  10. // 创建对象
  11. StringBuffer sb = new StringBuffer();
  12.  
  13. // 添加功能
  14. sb.append("hello").append("world").append("java");
  15. System.out.println("sb:" + sb);
  16.  
  17. // public StringBuffer deleteCharAt(int index):删除指定位置的字符,并返回本身
  18. // 需求:我要删除e这个字符,肿么办?
  19. // sb.deleteCharAt(1);
  20. // 需求:我要删除第一个l这个字符,肿么办?
  21. // sb.deleteCharAt(1);
  22.  
  23. // public StringBuffer delete(int start,int
  24. // end):删除从指定位置开始指定位置结束的内容,并返回本身
  25. // 需求:我要删除world这个字符串,肿么办?
  26. // sb.delete(5, 10);
  27.  
  28. // 需求:我要删除所有的数据
  29. sb.delete(0, sb.length());
  30.  
  31. System.out.println("sb:" + sb);
  32. }
  33. }

运行结果:

 
  1. sb:helloworldjava
  2. sb:

5. 替换功能

 
  1. package cn.itcast_04;
  2.  
  3. /*
  4. * StringBuffer的替换功能:
  5. * public StringBuffer replace(int start,int end,String str):从start开始到end用str替换
  6. */
  7. public class StringBufferDemo {
  8. public static void main(String[] args) {
  9. // 创建字符串缓冲区对象
  10. StringBuffer sb = new StringBuffer();
  11.  
  12. // 添加数据
  13. sb.append("hello");
  14. sb.append("world");
  15. sb.append("java");
  16. System.out.println("sb:" + sb);
  17.  
  18. // public StringBuffer replace(int start,int end,String
  19. // str):从start开始到end用str替换
  20. // 需求:我要把world这个数据替换为"节日快乐"
  21. sb.replace(5, 10, "节日快乐");
  22. System.out.println("sb:" + sb);
  23. }
  24. }

运行结果:

 
  1. sb:helloworldjava
  2. sb:hello节日快乐java

6. 反转功能

 
  1. package cn.itcast_05;
  2.  
  3. /*
  4. * StringBuffer的反转功能:
  5. * public StringBuffer reverse()
  6. */
  7. public class StringBufferDemo {
  8. public static void main(String[] args) {
  9. // 创建字符串缓冲区对象
  10. StringBuffer sb = new StringBuffer();
  11.  
  12. // 添加数据
  13. sb.append("霞青林爱我");
  14. System.out.println("sb:" + sb);
  15.  
  16. // public StringBuffer reverse()
  17. sb.reverse();
  18. System.out.println("sb:" + sb);
  19. }
  20. }

运行结果:

 
  1. sb:霞青林爱我
  2. sb:我爱林青霞

7. 截取功能

 
  1. package cn.itcast_06;
  2.  
  3. /*
  4. * StringBuffer的截取功能:注意返回值类型不再是StringBuffer本身了
  5. * public String substring(int start)
  6. * public String substring(int start,int end)
  7. */
  8. public class StringBufferDemo {
  9. public static void main(String[] args) {
  10. // 创建字符串缓冲区对象
  11. StringBuffer sb = new StringBuffer();
  12.  
  13. // 添加元素
  14. sb.append("hello").append("world").append("java");
  15. System.out.println("sb:" + sb);
  16.  
  17. // 截取功能
  18. // public String substring(int start)
  19. String s = sb.substring(5);
  20. System.out.println("s:" + s);
  21. System.out.println("sb:" + sb);
  22.  
  23. // public String substring(int start,int end)
  24. String ss = sb.substring(5, 10);
  25. System.out.println("ss:" + ss);
  26. System.out.println("sb:" + sb);
  27. }
  28. }

运行结果:

 
  1. sb:helloworldjava
  2. s:worldjava
  3. sb:helloworldjava
  4. ss:world
  5. sb:helloworldjava

8. String和StringBuffer的相互转换

 
  1. package cn.itcast_07;
  2.  
  3. /*
  4. * 为什么我们要讲解类之间的转换:
  5. * A -- B的转换
  6. * 我们把A转换为B,其实是为了使用B的功能。
  7. * B -- A的转换
  8. * 我们可能要的结果是A类型,所以还得转回来。
  9. *
  10. * String和StringBuffer的相互转换?
  11. */
  12. public class StringBufferTest {
  13. public static void main(String[] args) {
  14. // String -- StringBuffer
  15. String s = "hello";
  16. // 注意:不能把字符串的值直接赋值给StringBuffer
  17. // StringBuffer sb = "hello";
  18. // StringBuffer sb = s;
  19. // 方式1:通过构造方法
  20. StringBuffer sb = new StringBuffer(s);
  21. // 方式2:通过append()方法
  22. StringBuffer sb2 = new StringBuffer();
  23. sb2.append(s);
  24. System.out.println("sb:" + sb);
  25. System.out.println("sb2:" + sb2);
  26. System.out.println("---------------");
  27.  
  28. // StringBuffer -- String
  29. StringBuffer buffer = new StringBuffer("java");
  30. // String(StringBuffer buffer)
  31. // 方式1:通过构造方法
  32. String str = new String(buffer);
  33. // 方式2:通过toString()方法
  34. String str2 = buffer.toString();
  35. System.out.println("str:" + str);
  36. System.out.println("str2:" + str2);
  37. }
  38. }

运行结果:

 
  1. sb:hello
  2. sb2:hello
  3. ---------------
  4. str:java
  5. str2:java

编程要求

根据提示,在右侧编辑器补充代码,完成以下任务:

1.将stringExample转换成StringBuffer类

2.向转化后的StringBuffer增加字符串educode

3.删除5-8的字符串

4.将7-13的字符串替换成world

5.截取1-10的字符串并输出

6.反转字符串并输出

测试说明

平台会对你编写的代码进行测试:

测试输入:hello,educode,ilovelearnig 预期输出: 添加数据后:hello,educode,ilovelearnigeducode 删除5-8的字符串后:helloucode,ilovelearnigeducode 替换7-13的字符串后:helloucworldovelearnigeducode 截取1-10的字符串为:elloucwor 反转后的字符串为:edocudeginraelevodlrowcuolleh


开始你的任务吧,祝你成功!

 

package step2;
import java.util.Scanner;
public class StringBufferLearning {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String stringExample = scanner.next();
        // ---------------------Begin------------------------
        StringBuffer stringBuffer = new StringBuffer(stringExample);
        stringBuffer.append("educode");
        System.out.println(String.format("添加数据后:%s", stringBuffer));
        stringBuffer.delete(5, 8);
        System.out.println(String.format("删除5-8的字符串后:%s", stringBuffer));
        stringBuffer.replace(7, 13,"world");
        System.out.println(String.format("替换7-13的字符串后:%s", stringBuffer));
        System.out.println(String.format("截取1-10的字符串为:%s", stringBuffer.substring(1, 10)));
        stringBuffer.reverse();
        System.out.println(String.format("反转后的字符串为:%s", stringBuffer));
        // ---------------------End------------------------
    }
}

 

第3关:Math类

任务描述

本关任务:认识Math类的使用方法,完成以下任务:

1.求出变量value1的绝对值

2.求出value1的3次幂

3.求出value1的二次方根

4.求出value1的sin值

5.求出value1与value2中的较大者

相关知识

Math类基本知识

Math类是数学操作类,Math类提供了常用的一些数学函数,如:三角函数、对数、指数等。一个数学公式如果想用代码表示,则可以将其拆分然后套用Math类下的方法即可。

Math类中有两个静态常量PI和E,分别代表数学常量π和e。

 
  1. Math.abs(12.3); //12.3 返回这个数的绝对值
  2. Math.abs(-12.3); //12.3
  3.  
  4. Math.copySign(1.23, -12.3); //-1.23,返回第一个参数的量值和第二个参数的符号
  5. Math.copySign(-12.3, 1.23); //12.3
  6.  
  7. Math.signum(x); //如果x大于0则返回1.0,小于0则返回-1.0,等于0则返回0
  8. Math.signum(12.3); //1.0
  9. Math.signum(-12.3); //-1.0
  10. Math.signum(0); //0.0
  11.  
  12.  
  13. //指数
  14. Math.exp(x); //e的x次幂
  15. Math.expm1(x); //e的x次幂 - 1
  16.  
  17. Math.scalb(x, y); //x*(2的y次幂)
  18. Math.scalb(12.3, 3); //12.3*2³
  19.  
  20. //取整
  21. Math.ceil(12.3); //返回最近的且大于这个数的整数13.0
  22. Math.ceil(-12.3); //-12.0
  23.  
  24. Math.floor(12.3); //返回最近的且小于这个数的整数12.0
  25. Math.floor(-12.3); //-13.0
  26.  
  27. //x和y平方和的二次方根
  28. Math.hypot(x, y); //√(x²+y²)
  29.  
  30. //返回概述的二次方根
  31. Math.sqrt(x); //√(x) x的二次方根
  32. Math.sqrt(9); //3.0
  33. Math.sqrt(16); //4.0
  34.  
  35. //返回该数的立方根
  36. Math.cbrt(27.0); //3
  37. Math.cbrt(-125.0); //-5
  38.  
  39. //对数函数
  40. Math.log(e); //1 以e为底的对数
  41. Math.log10(100); //10 以10为底的对数
  42. Math.log1p(x); //Ln(x+ 1)
  43.  
  44. //返回较大值和较小值
  45. Math.max(x, y); //返回x、y中较大的那个数
  46. Math.min(x, y); //返回x、y中较小的那个数
  47.  
  48. //返回 x的y次幂
  49. Math.pow(x, y);
  50. Math.pow(2, 3); //即2³ 即返回:8
  51.  
  52. //随机返回[0,1)之间的无符号double值
  53. Math.random();
  54.  
  55. //返回最接近这个数的整数,如果刚好居中,则取偶数
  56. Math.rint(12.3); //12.0
  57. Math.rint(-12.3); //-12.0
  58. Math.rint(78.9); //79.0
  59. Math.rint(-78.9); //-79.0
  60. Math.rint(34.5); //34.0
  61. Math.rint(35.5); //36.0
  62.  
  63. Math.round(12.3); //与rint相似,返回值为long
  64.  
  65. //三角函数
  66. Math.sin(α); //sin(α)的值
  67. Math.cos(α); //cos(α)的值
  68. Math.tan(α); //tan(α)的值
  69.  
  70. //求角
  71. Math.asin(x/z); //返回角度值[-π/2,π/2] arc sin(x/z)
  72. Math.acos(y/z); //返回角度值[0~π] arc cos(y/z)
  73. Math.atan(y/x); //返回角度值[-π/2,π/2]
  74. Math.atan2(y-y0, x-x0); //同上,返回经过点(x,y)与原点的的直线和经过点(x0,y0)与原点的直线之间所成的夹角
  75.  
  76. Math.sinh(x); //双曲正弦函数sinh(x)=(exp(x) - exp(-x)) / 2.0;
  77. Math.cosh(x); //双曲余弦函数cosh(x)=(exp(x) + exp(-x)) / 2.0;
  78. Math.tanh(x); //tanh(x) = sinh(x) / cosh(x);
  79.  
  80. //角度弧度互换 360°角=2π弧度
  81. Math.toDegrees(angrad); //角度转换成弧度,返回:angrad * 180d / PI
  82.  
  83. Math.toRadians(angdeg); //弧度转换成角度,返回:angdeg / 180d * PI
  84.  
  85. Math.PI
 
  1. package cn.itcast.chapter05.example15;
  2. /**
  3. * Math类中比较常见的方法
  4. */
  5. public class Example15 {
  6. public static void main(String[] args) {
  7. System.out.println("计算绝对值的结果: " + Math.abs(-1));
  8. System.out.println("求大于参数的最小整数: " + Math.ceil(5.6));
  9. System.out.println("求小于参数的最大整数: " + Math.floor(-4.2));
  10. System.out.println("对小数进行四舍五入后的结果: " + Math.round(-4.6));
  11. System.out.println("求两个数的较大值: " + Math.max(2.1, -2.1));
  12. System.out.println("求两个数的较小值: " + Math.min(2.1, -2.1));
  13. System.out.println("生成一个大于等于0.0小于1.0随机值: " + Math.random());
  14. }
  15. }

编程要求

根据提示,在右侧编辑器补充代码,完成以下任务:

1.求出变量value1的绝对值

2.求出value1的3次幂

3.求出value1的二次方根

4.求出value1的sin值

5.求出value1与value2中的较大者

测试说明

平台会对你编写的代码进行测试:

测试输入:

81

-9 预期输出: value1=81, value2=-9 value1的绝对值为:81 value1的3次幂为:531441.000000 value1的2次方根为:9.000000 value1的sin值为:-0.629888 value1与value2中的较大者为:81


开始你的任务吧,祝你成功!

 

package step3;
import java.util.Scanner;
public class MathClass {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int value1 = scanner.nextInt();
int value2 = scanner.nextInt();
// ---------------------Begin------------------------
/**
1.求出变量value1的绝对值
2.求出value1的3次幂
3.求出value1的二次方根
4.求出value1的sin值
5.求出value1与value2中的较大者
* */
System.out.println(String.format("value1=%d, value2=%d", value1, value2));
System.out.println(String.format("value1的绝对值为:%d", Math.abs(value1)));
System.out.println(String.format("value1的3次幂为:%f", Math.pow(value1, 3)));
System.out.println(String.format("value1的2次方根为:%f", Math.sqrt(value1)));
System.out.println(String.format("value1的sin值为:%f", Math.sin(value1)));
System.out.println(String.format("value1与value2中的较大者为:%d", Math.max(value1, value2)));
// ---------------------End------------------------
}
}

 

第4关:Random类

任务描述

本关任务:掌握Random类的使用方法,完成以下任务:

1.生成5个整数并打印输出

2.生成5个double类型并打印输出

tip:Random类的种子需要设置为2022

相关知识

Random类

在JDK的java.util包中有一个Random类,它可以在指定的取值范围内随机产生数字。在Random类中提供了两个构造方法,具体如下表所示。

The table lists two constructors of the Random class. The first constructor has no parameters. The Random instance object created through it uses a random seed each time, so the random numbers generated by each object are different. If you want multiple Random instance objects created to generate the same sequence of random numbers, you can call the second constructor when creating the object and pass in the same seed.

Compared with Math's random() method, the Random class provides more methods to generate various pseudo-random numbers. It can not only generate random numbers of integer type, but also generate random numbers of floating point type. The following are listed in the table. Commonly used methods in the Random class.

The table lists the commonly used methods of the Random class. Among them, the nextDouble() method of the Random class returns a double type value between 0.0 and 1.0, and the nextFloat() method returns a float type value between 0.0 and 1.0. , nextInt(int n) returns a value between 0 (inclusive) and the specified value n (exclusive).

 
  1. package cn.itcast.chapter05.example16;
  2. import java.util.Random;
  3. /**
  4. * 使用构造方法Random()产生随机数
  5. */
  6. public class Example16 {
  7. public static void main(String args[]) {
  8. Random r = new Random(); // 不传入种子
  9. // 随机产生10个[0,100)之间的整数
  10. for (int x = 0; x < 10; x++) {
  11. System.out.println(r.nextInt(100));
  12. }
  13. }
  14. }
 
  1. package cn.itcast.chapter05.example17;
  2. import java.util.Random;
  3. /**
  4. * 使用构造方法Random(long seed)产生随机数
  5. */
  6. public class Example17 {
  7. public static void main(String args[]) {
  8. Random r = new Random(13); // 创建对象时传入种子
  9. // 随机产生10个[0,100)之间的整数
  10. for (int x = 0; x < 10; x++) {
  11. System.out.println(r.nextInt(100));
  12. }
  13. }
  14. }
 
  1. package cn.itcast.chapter05.example18;
  2. import java.util.Random;
  3. /**
  4. * Random类中的常用方法
  5. */
  6. public class Example18 {
  7. public static void main(String[] args) {
  8. Random r1 = new Random(); // 创建Random实例对象
  9. System.out.println("产生float类型随机数: " + r1.nextFloat());
  10. System.out.println("产生0~100之间int类型的随机数:" + r1.nextInt(100));
  11. System.out.println("产生double类型的随机数:" + r1.nextDouble());
  12. }
  13. }

Programming requirements

Follow the prompts and add code in the editor on the right to complete the following tasks:

1. Generate 5 integers and print the output

2. Generate 5 double types and print the output

tip: The seed of the Random class needs to be set to 2022

Test instruction

The platform will test the code you write:

No input


Start your mission and wish you success!

package step4;
import java.util.Random;
public class RandomClass {
public static void main(String[] args) {
// ---------------------Begin------------------------
Random random = new Random(2022);
for (int i = 0; i < 5; i++) {
System.out.println(random.nextInt());
}
for (int i = 0; i < 5; i++) {
System.out.println(random.nextDouble());
}
// ---------------------End------------------------
}
}

 

Level 5: Knowledge review

mission details

Task for this level: Review the main theoretical knowledge points of this chapter.

related information

In order to complete this mission, you need to review previously completed levels.

Programming requirements

Complete the questions as required based on relevant knowledge.

Test instruction

The platform will judge the answers you choose, and if you are correct, you will pass the test.


Start your mission and wish you success!

 

de16420e7cd44edebed0054701b839d8.png

 

 

Guess you like

Origin blog.csdn.net/weixin_62075168/article/details/127767042