根據身份證號判斷該人的年齡、性別、出生年月日
- 問題描述
- 解題思想
- 完整代碼
- 運行截圖
問題描述
- 輸入
身份證號輸入:123456200101011212
今年是哪一年:2021
- 輸出
該人的性別為:男性
出生年月為:2001年01月01日
年齡為:20周歲
解題思想
- 獲取資訊
- 資訊位置

- 獲取方法
- 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) + "周歲");
}
}
運行截圖

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/245197.html
標籤:java
