第二遍循环时从键盘接受值老是报错是怎么回事? 明明第一遍还过了
package com.ccqxt.practice;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* 综合案例 数组移位与统计
*
* @author 蓦然 2023-4-13
*
*/
public class StageFirst {
/**
* 插入数据方法
*/
public int[] insertData() {
Scanner sc = new Scanner(System.in);
int[] a = new int[10];
for (int i = 0; i < a.length - 1; i++) {
System.out.println("请输入第" + (i + 1) + "个数据:");
try {
a[i] = sc.nextInt();
} catch (InputMismatchException e) {
System.out.println("您的输入有误,请重新输入数字!");
sc.next();
i--;
}
}
sc.close();
return a;
}
/**
* 显示所有数据
*/
public void showDate(int[] a, int length) {
for (int i = 0; i < length; i++) {
System.out.print(a[i] + " ");
}
System.out.println("");
}
/**
* 在指定位置处插入数据
*/
public void insertAtArray(int[] a, int b, int c) {
for (int i = a.length - 1; i > c; i--) {
a[i] = a[i - 1];
}
a[c] = b;
}
/**
* 能被3整除的数据
*/
public void divThree(int[] a) {
String s = " ";
int count = 0;
for (int n : a) {
if (n % 3 == 0) {
s = n + s;
count++;
}
}
if (count == 0) {
System.out.println("数组中没有能被3整除的元素!");
} else {
System.out.println("能被3整除的数据为" + s);
}
}
/**
* 提示信息
*/
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) {
Scanner sc = new Scanner(System.in);
StageFirst sf = new StageFirst();
int num;
int[] a = null;
int numInsert = 0;
int numInsertAt = 0;
while (true) {
sf.notice();
System.out.println("请输入:");
num = sc.nextInt();
if (num == 0) {
System.out.println("退出!");
break;
}
switch (num) {
case 1:
a = sf.insertData();
System.out.println("数组元素为:");
sf.showDate(a, a.length - 1);
break;
case 2:
if (a != null) {
System.out.println("数组元素为:");
if (a[a.length - 1] == 0) {
sf.showDate(a, a.length - 1);
} else {
sf.showDate(a, a.length);
}
} else {
System.out.println("还未插入数据,请先插入数据再查询!");
}
break;
case 3:
System.out.print("请输入要插入的数据:");
try {
numInsert = sc.nextInt();
} catch (InputMismatchException e) {
System.out.println("您的输入有误,请重新输入数字!");
sc.next();
}
System.out.print("请输入要插入数据的位置:");
try {
numInsertAt = sc.nextInt();
} catch (InputMismatchException e) {
System.out.println("您的输入有误,请重新输入数字!");
sc.next();
}
for (int i = a.length; i > numInsertAt; i++) {
a[i] = a[i - 1];
}
a[numInsertAt] = numInsert;
break;
case 4:
sf.divThree(a);
break;
}
}
sc.close();
}
}
9
收起
正在回答 回答被采纳积分+1
2023版Java工程师
- 参与学习 人
- 提交作业 8790 份
- 解答问题 9886 个
综合就业常年第一,编程排行常年霸榜,北上广深月薪过万! 不需要基础,无需脱产即可学习,只要你有梦想,想高薪! 全新升级:技术栈升级(包含VUE3.0,ES6,Git)+项目升级(前后端联调与功能升级)
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星