Java keyboard enters the ages of multiple students, finds the location of the 15 students

Insert picture description herecode show as below:

package demo;

import java.util.Scanner;

public class Test5 {
    
    

	public static void main(String[] args) {
    
    
		// 键盘录入多个学生的年龄, 查找年龄为15的学生所在的位置
		// 假定输入5个学生的年龄
		Scanner sc = new Scanner(System.in);// 与键盘建立连接
		System.out.println("请输入五个学生的年龄:");
		int[] arr = new int[5];// 定义数组,数组长度为5

		// 循环录入年龄
		for (int i = 0; i < arr.length; i++) {
    
    
			arr[i] = sc.nextInt();
		}

		System.out.println("请输入需要查找的元素:");
		int num = sc.nextInt();// 得到需要查找的元素

		// 利用角标遍历数组查找所需要找到的元素
		for (int i = 0; i < arr.length; i++) {
    
    
			if (num == arr[i]) {
    
    
				System.out.println("查找同学位置在:" +"第"+ (i + 1) + "位");// 数组角标从0开始,所以i+1
			}
		}
		//如果所查找元素数组中没有,则打印结果
	}

}

Print results (can be found and not found):
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43462140/article/details/115321642