JAVA基础语法05
笔记
综合案例:数组移位与统计
- 案例需求
- 显示数据,预先设定好10个数据。
- 插入数据
- 在指定位置插入
- 可以被3整除
package com.demo01;
import java.util.Scanner;
/**
* 从键盘接收数据存储到数组中,并对数组进行管理
*
* @author zzh
*
*/
public class demo3 {
/**
* 插入数据
*
* @return a[]
*/
public int[] inSertData() {
int[] a = new int[10];
Scanner sc = new Scanner(System.in);
// 由于学习阶段留一位作为插入
for (int i = 0; i < a.length - 1; i++) {
System.out.print("请插入" + (i + 1) + "个数据:");
// 输入非数字的异常处理,使用在这边捕捉异常
try {
a[i] = sc.nextInt();
} catch (java.util.InputMismatchException e) {
System.out.println("输入的数据的格式有误,不能有非数字!");
// 原来接收第一次非数字的类型
sc.next();
i--; // 重新输入刚才数据
}
}
return a;
}
/**
* 显示数组中的所有元素
*
* @param a:数组
* @param length:显示元素个数
*/
// 显示数据
public void showData(int[] a, int length) {
for (int i = 0; i < length; i++) {
System.out.print(" " + a[i]);
}
System.out.println();
}
/**
* 在指定位置插入数据
*
* @param a:数组
* @param b:数据
* @param c:位置
*/
public void inSertAtArray(int[] a, int b, int c) {
// 从最后数据开始移动防止覆盖
for (int i = a.length - 1; i > c - 1; i--) {
a[i] = a[i - 1];
}
a[c - 1] = b;
}
/**
* 输出数组中能被3整除
*
* @param a
*/
public void divThree(int[] a,int length) {
String str = "";
int count = 0;
for(int i=0;i<length;i++) {
if(a[i]%3==0) {
str+=a[i]+" ";
count++;
}
}
if (count == 0) {
System.out.println("数组中没有被3整除!");
} else {
System.out.println("数组中可以被3整除的: " + str);
}
}
/**
* 通知
*/
public void notice() {
System.out.println("****************************");
System.out.println(" 1-- 插入数据");
System.out.println(" 2-- 显示所有数据数据");
System.out.println(" 3-- 指定位置插入数据");
System.out.println(" 4-- 查询被3整除的数据");
System.out.println(" 0-- 退出");
System.out.println("****************************");
}
public static void main(String[] args) {
demo3 dm = new demo3();
Scanner sc = new Scanner(System.in);
int input;
int[] a = null; // 初始化
int b, c,d=0;
while (true) {
dm.notice();
System.out.print("请输入对应的数据:");
try {
input = sc.nextInt();
} catch (java.util.InputMismatchException e) {
System.out.println("输入的数据的格式有误,不能有非数字!");
sc.next();
continue;
}
if (input == 0) {
System.out.println("退出程序!");
break;
}
switch (input) {
case 1:
if(d==0) {
// 插入数据
a = dm.inSertData();
System.out.println("数组元素:");
// 显示 数据
dm.showData(a, a.length - 1);
// d 用于标记最后一位元素是否插入
d++;
}else {
System.out.println("元素已经插入!");
}
break;
case 2:
if (a != null) {
System.out.println("数组元素:");
// 查看最后一个是否插入数据
if (a[a.length - 1] == 0) {
dm.showData(a, a.length - 1);
} else {
dm.showData(a, a.length);
}
} else {
System.out.println("请先插入数据!");
}
break;
case 3:
if (a != null) {
System.out.println("请输入插入数据:");
try {
b = sc.nextInt();
System.out.println("请输入插入位置:");
c = sc.nextInt();
} catch (java.util.InputMismatchException e) {
System.out.println("输入的数据的格式有误,不能有非数字!");
sc.next();
break;
}
dm.inSertAtArray(a, b, c);
dm.showData(a, a.length);
d--;
} else {
System.out.println("请先插入数据!");
}
break;
case 4:
if (a != null) {
if(d==1) {
dm.divThree(a, a.length-1);
}else {
dm.divThree(a, a.length);
}
} else {
System.out.println("请先插入数据!");
}
break;
}
}
}
}