繁体   English   中英

并行阵列,接受多个输入

[英]Parallel Arrays, Accepting multiple inputs

我目前正在尝试同时接受输入到两个数组中。 原因是在阵列的每个位置处的数据是对应的,例如。 名称和ID号。

String[] arr = new String[5];
    int[] arr1 = new int[5];

    Scanner kb = new Scanner(System.in);
    for(int i = 0; i<5; i++)
    {
        System.out.println("Enter a name:");
        arr[i] = kb.nextLine();
        System.out.println("Enter an ID:");
        arr1[i] = kb.nextInt();
    }

到目前为止,我已经有了这段代码,但是每当我运行它时,它都会要求输入一个名称和ID,然后要求两者都输入,但只会接受ID。

我似乎无法弄清楚为什么它不允许输入名称,它只是为此返回不兼容的数据类型错误。

从第二次迭代kb.nextLine() ,读取名称的kb.nextLine()kb.nextLine()输入\\n新行字符以输入ID整数。

实际的问题是nextInt()留下不是数字标记的char标记,因此它们留在stdin 每当其他任何方法尝试读取stdin ,该方法都会使用该输入。 nextLine方法在\\n之后返回,因此出现了问题。

因此,像这样更改代码:

String[] arr = new String[5];
        int[] arr1 = new int[5];

        Scanner kb = new Scanner(System.in);
        for(int i = 0; i<5; i++)
        {
            System.out.println("Enter a name:");
            arr[i] = kb.nextLine();
            System.out.println("Enter an ID:");
            arr1[i] = kb.nextInt();
            kb.nextLine();  //now this swallows new line
        }

或者,您可以使用两个扫描仪:如果您希望没有任何关系,例如为它们提供输入...根本没有冲突...我不知道这是否效率较低。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

public class Tester {

public static void main(String[] args) throws Exception {

String[] arr = new String[5];
        int[] arr1 = new int[5];

        Scanner kb = new Scanner(System.in);
        Scanner  bc=new Scanner(System.in);
        for(int i = 0; i<5; i++)
        {
            System.out.println("Enter a name:");
            arr[i] = kb.nextLine();
            System.out.println("Enter an ID:");
            arr1[i] = bc.nextInt();
        }}
}

您得到的行为是您描述的,因为nextInt()仅读取下一行的下一个整数,而不读取行的其余部分(为空)。因此,当循环返回并nextLine()方法时,它拾取(空)行的其余部分。 您应该在循环末尾放置一个kb.nextLine()方法,然后按照您的描述进行操作。

但是,以这种方式在并行数组中输入数据并不是最佳实践-您可能应该创建一个自定义类,然后将数组类型作为该类,或者使用ID映射到名称。

对我来说,这听起来像换行符仍在kb.nextInt()调用之后存储在输入缓冲区中,因此,当您调用kb.nextLine()它将以空字符串的形式读取此换行符,因为nextLine()函数将在遇到的第一个换行符处停止,因此您的程序会要求您提供下一个ID。
有效地跳过随后的任何时间询问姓名。

我可能会加入另一个kb.nextLine()后直接调用kb.nextInt()调用清除缓冲区中的\\ n(换行)字符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM