Java from Getting Started to Abandoning Chapter 6 (The use of Array to realize the election applet)

Today, I learned the Java array, which is similar to the list List in python. However, the difference is that the array Array needs to define the data type, can only store a single data type, and needs to define the storage length. List List can store a variety of data types, no need to define the storage length in advance. Below I have made a few small examples to share with you.

First, create a new Array.java file, and then add the following code to the Java file.

import java.util.*;

/**
    *      数组Array的例子
 * @author Mr.Pan_学狂
 * created time by 2021-2-28 
 */

public class Array{
    
    
	public static void main(String[] args) {
    
    
		//定义一个存储字符串的数组names,将数组元素写进去。
		String[] names = new String[] {
    
    "Jack","Mr.Pan_学狂","Mr.Jackel","Ms.Amy"};
		int Length = names.length;//获取数组的长度
		for(int i = 0;i < Length;i++) {
    
    
			System.out.println(names[i]);//打印数组中的每一个元素
		}
		test1();
	}
	
	public static void test1() {
    
    
		//定义一个整形数组number,定义number的存储长度为5
		int[] number = new int[5];
		int Length = number.length;//获取number数组的长度
		for(int i = 0;i < Length;i++) {
    
    
			number[i] = i+1;//当索引是0的时候值是1,以此类推。
		}
		String[] name = new String[] {
    
    "Jack","Peter","Mark","Ben","Amy"};
		System.out.println("候选人名单如下:");
		System.out.println("---------");//美观设计
		for(int i = 0;i < Length;i++) {
    
    
			if(i == 0) {
    
    
				System.out.println("|"+number[i]+"."+name[i]+" |");
			}
			else if(i == 1) {
    
    
				System.out.println("|"+number[i]+"."+name[i]+"|");
			}
			else if(i == 2) {
    
    
				System.out.println("|"+number[i]+"."+name[i]+" |");
			}
			else if(i == 3) {
    
    
				System.out.println("|"+number[i]+"."+name[i]+"  |");
			}
		}
		System.out.println("---------"+"\n");//加入\n的换行符
		System.out.println("请输入你的年龄:");
		Scanner impt = new Scanner(System.in);
		int age = impt.nextInt();
		if(age < 18) {
    
    
			System.out.println("未满18岁,不符合选举条件");
		}
		else if (age >= 18) {
    
    
			System.out.println("您现在有一票,请投票!");
			int select = impt.nextInt();
			int Index = select - 1;//创建数组对应的索引,将数组中的元素索引到。
			if(select == 1) {
    
    
				System.out.println("谢谢你,为"+name[Index]+"投了一票!");
			}
			else if(select == 2) {
    
    
				System.out.println("谢谢你,为"+name[Index]+"投了一票!");
			}
			else if(select == 3) {
    
    
				System.out.println("谢谢你,为"+name[Index]+"投了一票!");
			}
			else if(select == 4) {
    
    
				System.out.println("谢谢你,为"+name[Index]+"投了一票!");
			}
		}
	}
}

The results of the operation are as follows:
Insert picture description here
Insert picture description here
Finally, thank you all for coming to watch my article. There may be many improprieties in the article, and I hope to point out Hehaihan.

Guess you like

Origin blog.csdn.net/weixin_43408020/article/details/114208526