请问大神代码错在哪里
import java.util.Scanner;
public class Homework {
//插入数据
public int[] insertData() {
int[] a;
Scanner sc = new Scanner(System.in);
a = new int[10];
for(int i = 0; i < a.length - 1; i++) {
System.out.println("请输入第" + (i + 1) + "个数据:");
a[i] = sc.nextInt();
}
showData(a, 9);
sc.close();
return a;
}
//显示所有数据
public void showData(int[] a, int length) {
System.out.println("数组元素为:");
for(int i = 0; i < length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
//在指定位置处插入数据
public void insertAtArray(int[] a, int n, int k) {
for (int i = a.length - 1; i > k; i++) {
a[i] = a[i - 1];
}
a[k] = n;
showData(a, 10);
}
//查询能被3整除的数据
public void divthree(int[] a) {
System.out.println("数组中能被3整除的元素为:");
for(int n : a) {
if( n % 3 == 0)
{
System.out.print(n + " ");
}
}
}
//显示提示信息
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("********************************");
System.out.println("请输入对应的数据进行操作:");
}
public static void main(String[] args) {
Homework hw = new Homework();
Scanner sc1 = new Scanner(System.in);
int order = -1;
int length = 0;
int[] arr;
arr = new int[10];
int n, k;
while (true) {
hw.notice();
order = sc1.nextInt();
if(order == 0) {
System.out.println("程序结束!");
break;
}
switch(order) {
case 1: arr = hw.insertData(); break;
case 2:
for(int m : arr) {
if(m != 0) {
length++;
}
}
hw.showData(arr, length);
break;
case 3:
System.out.println("请输入要插入的数据:");
n = sc1.nextInt();
System.out.println("请输入要插入数据的位置:");
k = sc1.nextInt();
hw.insertAtArray(arr, n, k);
break;
case 4: hw.divthree(arr); break;
default: System.out.println("输入错误,请重试.");
}
}
sc1.close();
}
}每次到主调函数while循环里的order = sc1.nextInt();这一步就报错,请问是什么错误呢?
18
收起
正在回答
1回答
在你的insertData方法里,不能关闭Scanner对象,不然,当你在执行insertData方法时,就会清空Scanner对象的所有缓存,导致出现NoSuchElementException异常。
解决方案:把insertData方法里 sc.close()这句代码去掉。
如果解决了你的疑惑,请采纳,祝学习愉快~
Java零基础入门18
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星