04-数学函数、字符和字符串

04-数学函数、字符和字符串

  • 4.1 引言

    • 介绍数学函数、字符和字符串对象,并使用他们来开发程序。
  • 4.2 常用数学函数

    • 4.2.1 三角函数方法
      <center>Math类中的三角函数方法</center>
    方法 描述
    sin(radians) 返回以弧度为单位的角度的三角正弦函数值
    cos(radians) 返回以弧度为单位的角度的三角余弦函数值
    tan(radians) 返回以弧度为单位的角度的三角正切函数值
    toRadians(degrees) 将以度为单位的角度值转换为以弧度表示
    toDegrees(radians) 将以弧度为单位的角度值转换为以度表示
    asin(a) 返回以弧度为单位的角度的反三角正弦函数值
    acos(a) 返回以弧度为单位的角度的反三角余弦函数值
    atan(a) 返回以弧度为单位的角度的反三角正切函数值
    package chapter04;
    
    public class MathMethod {
        public static void main(String[] args){
            System.out.println(Math.toDegrees(Math.PI));
            System.out.println(Math.toRadians(30));
            System.out.println(Math.sin(0));
            System.out.println(Math.sin(Math.toRadians(270)));
            System.out.println(Math.sin(Math.PI / 6));
            System.out.println(Math.sin(Math.PI / 2));
            System.out.println(Math.cos(0));
            System.out.println(Math.cos(Math.PI / 6));
            System.out.println(Math.cos(Math.PI / 2));
            System.out.println(Math.asin(0.5));
            System.out.println(Math.acos(0.5));
            System.out.println(Math.atan(1.0));
        }
    }
    
    

    结果显示:

    180.0
    0.5235987755982988
    0.0
    -1.0
    0.49999999999999994
    1.0
    1.0
    0.8660254037844387
    6.123233995736766E-17
    0.5235987755982989
    1.0471975511965979
    0.7853981633974483
    
    Process finished with exit code 0
    
    
    • 4.2.2 指数函数方法
      <center>Math类中的指数函数方法</center>
      | 方法 |描述 |
      |--|--|
      |exp(x) |返回e的x次方(e^x) |
      | log(x) | 返回x的自然对数(Inx=loge(x) |
      | log10(x)| 返回x的以10为底的对数(log10(x))|
      | pow(a,b) |返回a的b次方(a^b) |
      | sqrt(x) | 对于x≥0的数字,返回x的平方根|
    package chapter04;
    
    public class MathMethod {
        public static void main(String[] args){
            System.out.println(Math.exp(3.5));
            System.out.println(Math.log(3.5));
            System.out.println(Math.log10(3.5));
            System.out.println(Math.pow(2,3));
            System.out.println(Math.pow(3,2));
            System.out.println(Math.pow(4.5,2.5));
            System.out.println(Math.sqrt(4));
            System.out.println(Math.sqrt(10.5));
        }
    }
    
    

    结果显示:

    33.11545195869231
    1.252762968495368
    0.5440680443502757
    8.0
    9.0
    42.95673695708276
    2.0
    3.24037034920393
    
    Process finished with exit code 0
    
    
    • 4.2.3 取整方法
      <center>Math类中的取整方法</center>
      | 方法 |描述 |
      |--|--|
      | ceil(x) | x向上取整为它最近的整数。该整数作为一个双精度值返回 |
      | floor(x)| x向下取整为它最近的整数。该整数作为一个双精度值返回|
      | rint(x)| x取整为它最接近的整数。如果x与两个整数的距离相等,偶数的整数作为一个双精度值返回 |
      | round(x)| 如果x是单精度数,返回(int)Math.floor(x+0.5);如果x是双精度数,返回(long)Math.floor(x+0.5)|
    package chapter04;
    
    public class MathMethod {
        public static void main(String[] args){
            System.out.println(Math.ceil(2.1));
            System.out.println(Math.ceil(2.0));
            System.out.println(Math.ceil(-2.0));
            System.out.println(Math.ceil(-2.1));
            System.out.println(Math.floor(2.1));
            System.out.println(Math.floor(2.0));
            System.out.println(Math.floor(-2.0));
            System.out.println(Math.floor(-2.1));
            System.out.println(Math.rint(2.1));
            System.out.println(Math.rint(-2.0));
            System.out.println(Math.rint(-2.1));
            System.out.println(Math.rint(2.5));
            System.out.println(Math.rint(4.5));
            System.out.println(Math.rint(-2.5));
            System.out.println(Math.round(2.6f));//return int
            System.out.println(Math.round(2.0));//return long 
            System.out.println(Math.round(-2.0f));//returns int 
            System.out.println(Math.round(-2.6));//return long 
            System.out.println(Math.round(-2.4));//return long 
        }
    }
    
    

    结果显示:

    3.0
    2.0
    -2.0
    -2.0
    2.0
    2.0
    -2.0
    -3.0
    2.0
    -2.0
    -2.0
    2.0
    4.0
    -2.0
    3
    2
    -2
    -3
    -2
    
    Process finished with exit code 0
    
    
    • 4.2.4 min、max和abs方法
      • min和max方法用于返回两个数(int、long、float和double型)的最小值和最大值。
      • abs函数以返回一个数(int、long、float和double)的绝对值。
    ```java
    package chapter04;
    
    public class MathMethod {
        public static void main(String[] args){
            System.out.println(Math.max(2,3));
            System.out.println(Math.min(2.5,4.6));
            System.out.println(Math.max(Math.max(2.5,4.6),Math.min(3,5.6)));
            System.out.println(Math.abs(-2));
            System.out.println(Math.abs(-2.1));
        }
    }
    
    ```
    结果显示:
    
    ```java
    3
    2.5
    4.6
    2
    2.1
    
    Process finished with exit code 0
    
    ```
- 4.2.5 random方法
    - random()方法生成大于等于0.0且小于1.0的double型随机数。
    

        ```java
        (int)(Math.random() * 10);//返回0-9之前的一个随机整数
                50 + (int)(Math.random() * 50);//返回50-99之间的一个随机数
                a + Math.random() * b;//返回a——a+b之间的一个随机数,不包括a+b
        ```
- 4.2.6 示例学习:计算三角形的角度
    - 提示用户输入三角形三个顶点的x和y坐标值,然后显示三个角。
    

        ```java
        package chapter04;
        
        import java.util.Scanner;
        
        public class ComputeAngles {
            public static void main(String[] args){
                Scanner input = new Scanner(System.in);
        
                System.out.print("Enter three points: ");
                double x1 = input.nextDouble();
                double y1 = input.nextDouble();
                double x2 = input.nextDouble();
                double y2 = input.nextDouble();
                double x3 = input.nextDouble();
                double y3 = input.nextDouble();
        
                double a = Math.sqrt((x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3));
                double b = Math.sqrt((x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 - y3));
                double c = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
        
                double A = Math.toDegrees(Math.acos((a * a - b * b - c * c) / (-2 * b * c)));
                double B = Math.toDegrees(Math.acos((b * b - a * a - c * c) / (-2 * a * c)));
                double C = Math.toDegrees(Math.acos((c * c - b * b - a * a) / (-2 * b * a)));
        
                System.out.println("The three angles are " + Math.round(A * 100) / 100.0 + " " + Math.round(B * 100) / 100.0 + " " + Math.round(C *100) / 100.0);
            }
        }
        
        ```
  • 4.3 字符数据类型和操作
    • 4.3.1 Unicode和ASCII码
      • 字符数据类型用于表示单个字符。
      • 字符串字面值必须括在双引号中。而字符字面值是括在单引号中的单个字符。因为“A”是一个字符串,而‘A’是一个字符。
      • 自增和自减操作符也可用在char型变量上,这会得到该字符之前或之后的Unicode字符。例如,下面的语句显示字符b:
        ```java
        char ch = 'a';
        System.out.println(++ch);
        ```
- 4.3.2 特殊字符的转义序列
![在这里插入图片描述](https://upload-images.jianshu.io/upload_images/24494503-a2d6a09f1a437de2?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
    - 反斜杠\被称为转义字符。它是一个特殊字符。
- 4.3.3 字符型数据与数字型数据之间的转换
    - char型数据可以转换成任意一种数值类型,反之亦然。将整数转换成char型数据时,只用到该数据的低十六位,其余部分都被忽略。
    

        ```java
        package chapter04;
        
        public class MathMethod {
            public static void main(String[] args){
                char ch1 = (char)0XAB0041;
                System.out.println(ch1);
        
                char ch2 = (char)65.25;
                System.out.println(ch2);
        
                int i = (int)'A';
                System.out.println(i);
        
                byte b = 'a';
                int j = 'a';
                byte bb = (byte)'\uFFF4';
        
                int z = '2' + '3';
                System.out.println("z is " + z);
                int x = 2 + 'a';
                System.out.println("x is " + x);
                System.out.println(x + " is the Unicode for character " + (char)x);
                System.out.println("Chapter " + '2');
            }
        }
        
        ```
        结果显示:
        
        ```java
        A
        A
        65
        z is 101
        x is 99
        99 is the Unicode for characterc
        Chapter 2
        
        Process finished with exit code 0
        
        ```
- 4.3.4 字符比较和测试
    - 两个字符可以使用关系操作符进行比较,如同比较两个数字一样。
    ![在这里插入图片描述](https://upload-images.jianshu.io/upload_images/24494503-085fd5a3690b8e56?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
        ```java
        package chapter04;
        
        public class CharacterMethod {
            public static void main(String[] args){
                System.out.println("isDidit('a') is " + Character.isDigit('a'));
                System.out.println("isLetter('a') is " + Character.isLetter('a'));
                System.out.println("isLowerCase('a') is " + Character.isLowerCase('a'));
                System.out.println("isUpperCase('a') is " + Character.isUpperCase('a'));
                System.out.println("toLowerCase('T') is " + Character.toLowerCase('T'));
                System.out.println("toUpperCase('q') is " + Character.toUpperCase('q'));
            }
        }
        
        ```
  • 4.4 String类型
    字符串是一个字符序列。String类型不是基本类型,而是引用类型。


    在这里插入图片描述
    • 4.4.1 获取字符串长度
      • 可以调用字符串的length()方法获取他的长度。
      • 为方便起见,Java允许在不创建新变量的情况下,使用字符串字面值直接饮用字符串。这样“Welcome to Java”.length()是正确的,它返回15.注意,“”表示空字符串,并且.length()为0。
    • 4.4.2 从字符串中获取字符
      • 方法s.charAt(index)可用于提取字符串s中的某个特定字符。
      • 在字符串s中越界访问字符是一个常见的程序设计错误。为了避免此类错误,要确保使用的下标不会超过s.length()-1。
    • 4.4.3 连接字符串
      • 加号(+)也可以用于连接字符串和数组。在这种情况下,先将数字转换成字符串,然后再进行连接。i,若要用加号实现连接的功能,至少要有一个操作数必须为字符串。
    • 4.4.4 字符串的转换
      • 方法trim()通过删除字符串两端的空白字符返回一个新字符串。字符‘ ’、\t、\f、\r或者\n被称为空白字符。
    • 4.4.5 从控制台读取字符串
      • 将使用方法next()、nextByte()、nextShort()、nextInt()、nextLong()、nextFloat()和nextDouble()的输入称为基于标记的输入,因为他们读取采用空白字符分隔的单个元素,而不是读取整行。nextLine()方法称为基于行的输入。
    • 4.4.6 从控制台读取字符
      • 调用nextLine()方法读取一个字符串,然后在字符串上调用charAt(0)来返回一个字符。
    • 4.4.7 字符串比较


      在这里插入图片描述
      package chapter04;
      
      import java.util.Scanner;
      
      public class OrderTwoCities {
          public static void main(String[] args){
              Scanner input = new Scanner(System.in);
              System.out.print("Enter the first city: ");
              String city1 = input.nextLine();
              System.out.print("Enter the second city: ");
              String city2 = input.nextLine();
              if (city1.compareTo(city2) < 0)
                  System.out.println("The cities in alphabetical order are " + city1 + " " + city2);
              else
                  System.out.println("The cities in alphabetical order are " + city2 + " " + city1);
          }
      }
      
      
    • 4.4.8 获得子字符串


      在这里插入图片描述
      • 如果beginIndex为endIndex,substring(beginIndex,endIndex)返回一个长度为0的空字符串。如果beginIndex>endIndex,将发生运行错误。
    • 4.4.9 获取字符串中的字符或者子串


      在这里插入图片描述
    • 4.4.10 字符串和数字间的转换
    ```java
    package chapter04;
    
    public class StringToInteger {
        public static void main(String[] args){
            String intString = "123";
            int intValue = Integer.parseInt(intString);
            System.out.println(intValue);
            String doubleString = "3.1415926";
            double doubleValue = Double.parseDouble(doubleString);
            System.out.println(doubleValue);
            int number = 222;
            String s = number + "";
            System.out.println(s);
        }
    }
    
    ```
  • 4.5 示例学习
    • 4.5.1 猜测生日


      在这里插入图片描述
      package chapter04;
      
      import java.util.Scanner;
      
      public class GuessBirthday {
          public static void main(String[] args){
              String set1 = "1 3 5 7\n" + "9 11 13 15\n" + "17 19 21 23\n" + "25 27 29 31";
              String set2 = "2 3 6 7\n" + "10 11 14 15\n" + "18 19 22 23\n" + "26 27 30 31";
              String set3 = "4 5 6 7\n" + "12 13 14 15\n" + "20 21 22 23\n" + "28 29 30 31";
              String set4 = "8 9 10 11\n" + "12 13 14 15\n" + "24 25 26 27\n" + "28 29 30 31";
              String set5 = "16 17 18 19\n" + "20 21 22 23\n" + "24 25 26 27\n" + "28 29 30 31";
      
              int day = 0;
      
              Scanner input = new Scanner(System.in);
      
              System.out.print("Is you birthday in Set1?\n");
              System.out.print(set1);
              System.out.print("\nEnter 0 for No and 1 for Yes: ");
              int answer = input.nextInt();
      
              if (answer == 1)
                  day += 1;
      
              System.out.print("\nIs you birthday in Set2?\n");
              System.out.print(set2);
              System.out.print("\nEnter 0 for No and 1 for Yes: ");
              answer = input.nextInt();
      
              if (answer == 1)
                  day += 2;
      
              System.out.print("\nIs you birthday in Set3?\n");
              System.out.print(set3);
              System.out.print("\nEnter 0 for No and 1 for Yes: ");
              answer = input.nextInt();
      
              if (answer == 1)
                  day += 4;
      
              System.out.print("\nIs you birthday in Set4?\n");
              System.out.print(set4);
              System.out.print("\nEnter 0 for No and 1 for Yes: ");
              answer = input.nextInt();
      
              if (answer == 1)
                  day += 8;
      
              System.out.print("\nIs you birthday in Set5?\n");
              System.out.print(set5);
              System.out.print("\nEnter 0 for No and 1 for Yes: ");
              answer = input.nextInt();
      
              if (answer == 1)
                  day += 16;
              System.out.println("\nYour birthday is " + day + "!");
          }
      }
      
      
      在这里插入图片描述
    • 4.5.2 将十六进制数转换为十进制

    ```java
    package chapter04;
    
    import java.util.Scanner;
    
    public class HexDigit2Dec {
        public static void main(String[] args){
            Scanner input = new Scanner(System.in);
            System.out.print("Enter a hex digit: ");
            String hexString = input.nextLine();
    
            if (hexString.length() != 1){
                System.out.println("You must enter exactly one character");
                System.exit(1);
            }
    
            char ch = Character.toUpperCase(hexString.charAt(0));
            if ('A' <= ch && ch <= 'F'){
                int value = ch - 'A' + 10;
                System.out.println("The decimal value for hex digit " + ch + " is " + value);
            }
            else if (Character.isDigit(ch)){
                System.out.println("The decimal value for hex digit " + ch + " is " + ch);
            }
            else{
                System.out.println(ch + " is an invalid input");
            }
        }
    }
    
    ```
- 4.5.3 使用字符串修改彩票程序
![在这里插入图片描述](https://upload-images.jianshu.io/upload_images/24494503-fb6bdd02ae00432e?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
    ```java
    package chapter04;
    
    import java.util.Scanner;
    
    public class LotteryUsingStrings {
        public static void main(String[] args){
            String lottery = "" + (int)(Math.random() * 10) + (int)(Math.random() * 10);
    
            Scanner input = new Scanner(System.in);
            System.out.print("Enter your lottery pick (two digits): ");
            String guess = input.nextLine();
    
            char lotteryDigit1 = lottery.charAt(0);
            char lotteryDigit2 = lottery.charAt(1);
    
            char guessDigit1 = guess.charAt(0);
            char guessDigit2 = guess.charAt(1);
    
            System.out.println("The lottery number is " + lottery);
    
            if (guess.equals(lottery))
                System.out.println("Exact match:you win $10,000");
            else if (guessDigit2 == lotteryDigit1 && guessDigit1 == lotteryDigit2)
                System.out.println("Match all digits:you win $3,000");
            else if (guessDigit1 == lotteryDigit1 || guessDigit1 == lotteryDigit2 || guessDigit2 == lotteryDigit2 || guessDigit2 == lotteryDigit1)
                System.out.println("Match one digit:yuo win $1,000");
            else
                System.out.println("Sorry,no match");
        }
    }
    
    ```
  • 4.6 格式化控制台输出
    • 可以使用System.out.printf方法在控制台上显示格式化输出。
    • printf中的f代表格式(format),暗示着方法将以某种格式打印。调用这个方法的语法是:
    ```java
    System.out.printf(format,item1,item2,...,itemk);
    ```
[图片上传失败...(image-edf74e-1601915130907)]
在这里插入图片描述

- 如果项需要比指定宽度更多的空间,宽度自动增加。例如,下面的代码:

    ```java
    System.out.printf("%3d#%2s#%4.2f\n",1234,"Java",51.6653);
    ```
    结果显示:
    
    ```java
    1234#Java#51.67
    ```
- 如果要显示一个带有逗号的数字,可以在数字限定符前面添加一个逗号。

    
    ```java
    System.out.printf("%,8d %,10.1f\n",12345678,12345678.263);
    ```
    结果显示:
    
    ```java
    12,345,678 12,345,678.3
    ```
- 如果要在数字前面添加0而不是空格来凑齐位数,可以在一个数字限定符前面添加0。

    
    ```java
    System.out.printf("%08d %08.1f\n",1234,5.63);
    ```
    结果显示:
    
    ```java
    00001234 000005.6
    ```
- 默认情况下,输出是右对齐的。可以在格式限定符中放一个减号(-),指定该项在指定域中的出书是左对齐的。


    ```java
    System.out.printf("%-8d%-8s%-8.1f\n",1234,"Java",5.63);
    ```
    结果显示:
    
    ```java
    1234    Java    5.6     
    ```
- 条目与格式标识符必须在类型上严格匹配。对应于格式标识符%f或%e的条目必须是浮点型值,可以使用%.2f来指定一个小数点后两位的浮点数值,而是用%0.2f是不正确 。
package chapter04;

public class FormatDemo {
    public static void main(String[] args){
        System.out.printf("%-10s%-10s%-10s%-10s%-10s\n","Degrees","Radians","Sine","Cosine","Tangent");

        int degrees = 30;
        double radians = Math.toRadians(degrees);
        System.out.printf("%-10d%-10.4f%-10.4f%-10.4f%-10.4f\n",degrees,radians,Math.sin(radians),Math.cos(radians),Math.tan(radians));

        degrees = 60;
        radians = Math.toRadians(degrees);
        System.out.printf("%-10d%-10.4f%-10.4f%-10.4f%-10.4f\n",degrees,radians,Math.sin(radians),Math.cos(radians),Math.tan(radians));
    }
}

结果显示:

Degrees   Radians   Sine      Cosine    Tangent   
30        0.5236    0.5000    0.8660    0.5774    
60        1.0472    0.8660    0.5000    1.7321    

Process finished with exit code 0

  • 编程小习题
    • 1、
      在这里插入图片描述
      package chapter04;
      
      import java.util.Scanner;
      
      public class Code_01 {
          public static void main(String[] args){
              Scanner input = new Scanner(System.in);
              System.out.print("Enter the length from the center to a vertex: ");
              double r = input.nextDouble();
              double s = 2 * r * Math.sin(Math.PI / 5);
              double area = 5 * s * s / (4 * Math.tan(Math.PI / 5));
              System.out.printf("The area of the pentagon is %.2f",area);
          }
      }
      
      
    • 2、
      在这里插入图片描述
      package chapter04;
      
      public class Code_06 {
          public static void main(String[] args){
              double x1, y1, x2, y2, x3, y3;
              double angleA,angleB,angleC,alpha;
              double a,b,c;
      
              alpha = Math.random() * (2 * Math.PI);
              x1 = 40 * Math.cos(alpha);
              y1 = 40 * Math.sin(alpha);
      
              alpha = Math.random() * (2 * Math.PI);
              x2 = 40 * Math.cos(alpha);
              y2 = 40 * Math.sin(alpha);
      
              alpha = Math.random() * (2 * Math.PI);
              x3 = 40 * Math.cos(alpha);
              y3 = 40 * Math.sin(alpha);
      
              a = Math.sqrt(Math.pow(x1 - x2, 2)+Math.pow(y1 - y2, 2));
              b = Math.sqrt(Math.pow(x1 - x3, 2)+Math.pow(y1 - y3, 2));
              c = Math.sqrt(Math.pow(x3 - x2, 2)+Math.pow(y3 - y2, 2));
      
              angleA = Math.toDegrees(Math.acos((a * a - b * b - c * c) / (-2 * b * c)));
              angleB = Math.toDegrees(Math.acos((b * b - a * a - c * c) / (-2 * a * c)));
              angleC = Math.toDegrees(Math.acos((c * c - b * b - a * a) / (-2 * b * a)));
      
              System.out.printf("The first angle in degree is %.2f\n", angleA);
              System.out.printf("The second angle in degree is %.2f\n", angleB);
              System.out.printf("The third angle in degree is %.2f", angleC);
          }
      }
      
      
    • 3、[图片上传失败...(image-75be4e-1601915130907)]
      package chapter04;
      
      import java.util.Scanner;
      
      public class Code_08 {
          public static void main(String[] args){
              Scanner input = new Scanner(System.in);
              System.out.print("Enter an ASCII code : ");
              int number = input.nextInt();
              System.out.println("The character for ASCII code " + number + " is " + (char)number);
          }
      }
      
      
    • 4、[图片上传失败...(image-30ecef-1601915130907)]
      package chapter04;
      
      import java.util.Scanner;
      
      public class Code_09 {
          public static void main(String[] args){
              Scanner input = new Scanner(System.in);
              System.out.print("Enter a character: ");
              String str = input.nextLine();
              char character = str.charAt(0);
              System.out.println("The Unicode for the character " + character + " is " + (int)character);
          }
      }
      
      
    • 5、
      在这里插入图片描述
      package chapter04;
      
      import java.util.Scanner;
      
      public class Code_15 {
          public static void main(String[] args){
              Scanner input = new Scanner(System.in);
              System.out.print("Enter a letter: ");
              String str = input.nextLine();
              char letter = str.toUpperCase().charAt(0);
              if (letter == 'A' || letter == 'B' || letter == 'C')
                  System.out.println("The corresponding number is 2");
              else if (letter == 'D' || letter == 'E' || letter == 'F')
                  System.out.println("The corresponding number is 3");
              else if (letter == 'G' || letter == 'H' || letter == 'I')
                  System.out.println("The corresponding number is 4");
              else if (letter == 'J' || letter == 'K' || letter == 'L')
                  System.out.println("The corresponding number is 5");
              else if (letter == 'M' || letter == 'N' || letter == 'O')
                  System.out.println("The corresponding number is 6");
              else if (letter == 'P' || letter == 'Q' || letter == 'R' || letter == 'S')
                  System.out.println("The corresponding number is 7");
              else if (letter == 'T' || letter == 'U' || letter == 'V')
                  System.out.println("The corresponding number is 8");
              else
                  System.out.println("The corresponding number is 9");
          }
      }
      
      
    • 6、[图片上传失败...(image-f286eb-1601915130907)]
      package chapter04;
      
      public class Code_16 {
          public static void main(String [] args){
              System.out.println((char) ((int)(Math.random() * 26) + 65));
          }
      }
      
      
    • 7、
      在这里插入图片描述
      package chapter04;
      
      import java.util.*;
      
      public class Code_21 {
          public static void main(String[] args){
              String ssnString;
      
              System.out.print("Enter a SSN: ");
              Scanner input = new Scanner(System.in);
              ssnString = input.nextLine();
      
              if(ssnString.length() == 11)
              {
                  if(Character.isDigit(ssnString.charAt(0))
                          && Character.isDigit(ssnString.charAt(1))
                          && Character.isDigit(ssnString.charAt(2))
                          && ssnString.charAt(3) == '-'
                          && Character.isDigit(ssnString.charAt(4))
                          && Character.isDigit(ssnString.charAt(5))
                          && ssnString.charAt(6) == '-'
                          && Character.isDigit(ssnString.charAt(7))
                          && Character.isDigit(ssnString.charAt(8))
                          && Character.isDigit(ssnString.charAt(9))
                          && Character.isDigit(ssnString.charAt(10)))
      
                      System.out.println(ssnString + " is a valid social security number");
                  else
                      System.out.println(ssnString + " is an invalid social security number");
              }
              else
                  System.out.println(ssnString + " is an invalid social security number");
      
              input.close();
          }
      }
      
      
    • 8、
      在这里插入图片描述
      package chapter04;
      
      import java.util.*;
      
      public class Code_22 {
          public static void main(String[] args) {
              String string1,string2;
      
              System.out.print("Enter string s1: ");
              Scanner input = new Scanner(System.in);
              string1 = input.nextLine();
      
              System.out.print("Enter string s2: ");
              string2 = input.nextLine();
      
              System.out.println(string1.contains(string2)
                      ?string2 + " is a substring of " + string1
                      :string2 + " is not a substring of " + string1);
              input.close();
          }
      }
      
      
    • 9、
      在这里插入图片描述
      package chapter04;
      
      import java.util.*;
      
      public class Code_24 {
          public static void main(String[] args) {
              String city1,city2,city3;
      
              Scanner inputScanner = new Scanner(System.in);
      
              System.out.print("Enter the first city: ");
              city1 = inputScanner.nextLine();
              System.out.print("Enter the second city: ");
              city2 = inputScanner.nextLine();
              System.out.print("Enter the third city: ");
              city3 = inputScanner.nextLine();
      
              if(city1.compareTo(city2) > 0) // city1 > city2
              {
                  if(city2.compareTo(city3) > 0) // city2 > city3
                      System.out.println("The three cities in alphabetical order are " + city1 + " " + city2 + " " + city3);
                  else //city2 < city3
                  {
                      if(city1.compareTo(city3) > 0) // city1 > city3
                          System.out.println("The three cities in alphabetical order are " + city2 + " " + city3 + " " + city1);
                      else // city1 < city3
                          System.out.println("The three cities in alphabetical order are " + city2 + " " + city1 +  " " + city3);
                  }
              }
              else // city1 < city2
              {
                  if(city1.compareTo(city3) > 0) // city1 > city3
                      System.out.println("The three cities in alphabetical order are " + city3 + " " + city1 + " " + city2);
                  else //city1 < city3
                  {
                      if(city2.compareTo(city3) > 0) // city2 > city3
                          System.out.println("The three cities in alphabetical order are " + city1 + " " + city3 + " " + city2);
                      else // city2 < city3
                          System.out.println("The three cities in alphabetical order are " + city1 + " " + city2 + " " + city3);
                  }
              }
      
              inputScanner.close();
          }
      }
      
      
    • 10、[图片上传失败...(image-a71146-1601915130907)]
      package chapter04;
      
      public class Code_25 {
          public static void main(String[] args) {
      
              char char1,char2,char3,char4,char5,char6,char7;
      
              char1 = (char)(65 + (int)(Math.random() * 26));
              char2 = (char)(65 + (int)(Math.random() * 26));
              char3 = (char)(65 + (int)(Math.random() * 26));
      
              char4 = (char)(48 + (int)(Math.random() * 10));
              char5 = (char)(48 + (int)(Math.random() * 10));
              char6 = (char)(48 + (int)(Math.random() * 10));
              char7 = (char)(48 + (int)(Math.random() * 10));
      
              System.out.println("The vehicle plate numbers is " + char1+char2+char3+char4+char5+char6+char7);
          }
      }
      
      
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,482评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,377评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,762评论 0 342
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,273评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,289评论 5 373
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,046评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,351评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,988评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,476评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,948评论 2 324
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,064评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,712评论 4 323
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,261评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,264评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,486评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,511评论 2 354
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,802评论 2 345