【发布时间】:2019-10-07 15:17:18
【问题描述】:
import java.util.Scanner;
public class TeacherCoins {
public static void main(String[] args){
int k;
System.out.print("Enter total number of coins :");
Scanner sc = new Scanner(System.in);
k =sc.nextInt();
int [] arr= new int[k-1];
System.out.print("Enter array :");
for(int i=0;i<=(k-1);i++)
{
Scanner sc1 = new Scanner(System.in);
arr[i] =sc1.nextInt();
}
for(int element :arr)
{
System.out.println("Print array");
System.out.println(element);
}
}
我正在使用 Scanner 类提供输出。但是没有打印数组。
【问题讨论】:
-
请修正代码格式。为什么要在 for 循环体内声明
Scanner对象?为什么要使用k - 1元素创建数组? -
作为一个小提示,您不需要构建第二个扫描仪。您可以继续使用以前的扫描仪
sc。 -
我必须给数组输入,所以我创建了扫描仪类。我已移除并尝试关闭扫描仪。它仍然没有打印数组。
-
你溢出了数组,因为它比它需要的小一个元素。所以你得到一个终止你的程序的异常。
int [] arr= new int[k];修复它。
标签: java