用于在用户使用Java输入和打印时跳过索引0的循环

用于在用户使用Java输入和打印时跳过索引0的循环,java,arrays,Java,Arrays,例如,我输入了3个学生的尺寸。在打印时,它也会跳过控制台中的索引0 我一点也不知道它为什么跳过索引0?谢谢你的帮助 导入java.util.array; 导入java.util.Scanner; 类字符串{ 公共静态无效字符串[]args{ 扫描仪控制台=新的ScannerSystem.in; System.out.print输入学生人数:; int studentSize=console.nextInt; 字符串[]arrName=新字符串[studentSize]; 对于int i=0;i

例如,我输入了3个学生的尺寸。在打印时,它也会跳过控制台中的索引0

我一点也不知道它为什么跳过索引0?谢谢你的帮助

导入java.util.array; 导入java.util.Scanner; 类字符串{ 公共静态无效字符串[]args{ 扫描仪控制台=新的ScannerSystem.in; System.out.print输入学生人数:; int studentSize=console.nextInt; 字符串[]arrName=新字符串[studentSize];
对于int i=0;i此跳过的原因是由于console.nextInt和console.nextLine的行为不同,如下所示:

console.nextInt读取输入的整数值,无论是否按enter键换行

console.nextLine读取整行内容,但正如您之前在输入数组大小时所做的那样

3被接受为数组的大小,当您点击enter键时,它被接受为数组的第一个值,这是一个空格,或者我可以说它被称为

以下是这方面的两项决议:

在每个console.nextLine之后放置一个console.nextLine调用,以使用该行的其余部分(包括换行符)

或者,更好的方法是通过Scanner.nextLine读取输入,并将输入转换为所需的正确格式。您可以使用int studentSize=integer.parseIntconsole.nextLine方法将其转换为整数。用try-catch将其包围

问题在于console.nextInt,此函数仅读取int值。因此,在循环console.nextLine中的代码中,第一次跳过获取输入。只需将console.nextLine放在console.nextInt之后 你可以解决这个问题

public static void main(String [] args){
        Scanner console = new Scanner(System.in);

        System.out.print("Enter Student Size: ");
        int studentSize = console.nextInt();
        console.nextLine();
        String [] arrName = new String[studentSize];

        for (int i=0; i<arrName.length; i++){
            System.out.print("Enter student name: ");
            String nameString = console.nextLine();
            arrName[i] = nameString;
        }

        System.out.print(Arrays.toString(arrName));

        //Closing Braces for Class and Main

    }