根據身份證号判斷該人的年齡、性别、出生年月日
- 問題描述
- 解題思想
- 完整代碼
- 運作截圖
問題描述
- 輸入
身份證号輸入:123456200101011212
今年是哪一年:2021
- 輸出
該人的性别為:男性
出生年月為:2001年01月01日
年齡為:20周歲
解題思想
- 擷取資訊
- 資訊位置
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiIXZ05WZj91YpB3IwczX0xiRGZkRGZ0Xy9GbvNGL2EzXlpXazxSP9cXTxEFVPlXWq5EM4wmYwhGWhxGZzwEMW1mY1RzRapnTtxkb5ckYplTeMZTTINGMShUYfRHelRHLwEzX39GZhh2css2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xyayFWbyVGdhd3LcV2Zh1Wa9M3clN2byBXLzN3btg3Pn5GcukzM1MTNzYTMyATMwEjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
- 擷取方法
-
substring()(擷取新的字元串)
substring()方法連接配接
根據身份證号判斷該人的年齡、性别、出生年月日問題描述解題思想完整代碼運作截圖
String year = (String) id.subSequence(6, 10);
String month = (String) id.subSequence(10, 12);
String day = (String) id.subSequence(12, 14);
String sex = (String) id.subSequence(16, 17);
- 将字元串轉變成整形 Integer.parseInt()
字元串轉變成整形連接配接
我們會在計算周歲、判斷性别的時候,用到加減,是以須将字元串變成整形
int y = Integer.parseInt(year);
int s = Integer.parseInt(sex);
完整代碼
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("請輸入身份證号:");
String id = sc.next();
System.out.print("今年是那一年:");
int n=sc.nextInt();
String year = (String) id.subSequence(6, 10);
String month = (String) id.subSequence(10, 12);
String day = (String) id.subSequence(12, 14);
String sex = (String) id.subSequence(16, 17);
int y = Integer.parseInt(year);
int s = Integer.parseInt(sex);
System.out.print("該人的性别為:");
if (s % 2 == 0) {
System.out.println("女性");
} else {
System.out.println("男性");
}
System.out.println("出生年月為:" + year + "年" + month + "月" + day + "日");
System.out.println("年齡為:" + (n - y) + "周歲");
}
}