通过扫描仪获取输入并仅不使用for循环创建数组

时间:2018-12-16 18:17:30

标签: java arrays

private static int[] arr;
public static void inputarrays() {
    Scanner scan = new Scanner(System.in);

    System.out.println("length of an array");

    int x = scan.nextInt();
    arr = new int[x];

    System.out.println("values of an array");
    for(int n = 0; n < x; x++) {
        arr[n] = scan.nextInt();
    }
}

我查看了如何编写代码来获取用户输入并创建一个像这样的数组:  Java - Creating an array from user input

看来我的代码与链接的代码相同,这意味着它应该可以正常工作。但是,当我输入数组的值时,扫描仪永远不会关闭。我尝试了scan.close(),但没有成功。另外,我不能为此使用try&exception。

2 个答案:

答案 0 :(得分:1)

此方法有效,请尝试:

\\DESKTOP-54P9Q3C\root\cimv2:Win32_PnPEntity.DeviceID="BTHLE\\DEV_BC83851FE704\\7&222CF7DF&0&BC83851FE704"
 Availability:
 Caption: Surface Dial
 ClassGuid: {e0cbf06c-cd8b-4647-bb8a-263b43f0f974}
 CompatibleID: System.String[]
 ConfigManagerErrorCode: 0
 ConfigManagerUserConfig: False
 CreationClassName: Win32_PnPEntity
 Description: Bluetooth LE Device
 DeviceID: BTHLE\DEV_BC83851FE704\7&222CF7DF&0&BC83851FE704
 ErrorCleared:
 ErrorDescription:
 HardwareID: System.String[]
 InstallDate:
 LastErrorCode:
 Manufacturer: Microsoft
 Name: Surface Dial
 PNPClass: Bluetooth
 PNPDeviceID: BTHLE\DEV_BC83851FE704\7&222CF7DF&0&BC83851FE704
 PowerManagementCapabilities:
 PowerManagementSupported:
 Present: True
 Service: BthLEEnum
 Status: OK
 StatusInfo:
 SystemCreationClassName: Win32_ComputerSystem
 SystemName: DESKTOP-54P9Q3C
  1. private static int[] arr; public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("length of an array"); int x = scan.nextInt(); scan.nextLine(); arr = new int[x]; System.out.println("values of an array"); for(int n=0; n<x; n++){ arr[n]=scan.nextInt(); scan.nextLine(); } } 更改为x++,因为n++是循环的索引
  2. 在每次调用n之后添加了scan.nextLine();,以便完全消耗每条输入行。

答案 1 :(得分:-2)

您在循环中使用了n,因此您必须使用n++而不是x++

private static int[] arr;
public static void inputarrays() {
    Scanner scan = new Scanner(System.in);

    System.out.println("length of an array");

    int x = scan.nextInt();
    arr = new int[x];
    System.out.println("values of an array");
    for(int n = 0; n < x; n++) {
        arr[n] = scan.nextInt();
    }
}

它应该以这种方式工作。