使用扫描仪初始化的数组长度

时间:2014-10-29 12:22:08

标签: java arrays java.util.scanner

我正在尝试让用户输入int,然后输入该数量的名称。

程序以反向顺序打印这些名称。但是,当我使用Scanner时,我存储这些名称的数组总是被创建为一个太小的元素。当我自己分配一个号码时,我没有这个问题。是Scanner还是我做错了什么?

import java.util.Scanner;

class forTester {
    public static void main (String str[]) {
        Scanner scan = new Scanner(System.in); 

        //Why does this commented code scan only one less name than expected???
        /*
        System.out.println("How many names do you want to enter?");
        int num = scan.nextInt();
        System.out.println("Enter " + num + " Names:");
        String names[] = new String[num];
        */ 
        //Comment out the next two lines if you use the four lines above.
        System.out.println("Enter " + 4 + " Names:");
        String names[] = new String[4];

        // The code below works fine.
        for (int i = 0; i < names.length; i++) {
            names[i]=scan.nextLine(); 
        }

        for(int i = names.length - 1; i >= 0; i--) {
            for(int p = names[i].length() - 1; p >= 0; p--) {
                System.out.print(names[i].charAt(p));
            }
            System.out.println("");
        }
    }
}

2 个答案:

答案 0 :(得分:0)

将评论代码更改为:

   System.out.println("How many names do you want to enter?");
   int num = scan.nextInt();
   System.out.println("Enter " + num + " Names:");
   String names[] = new String[num];
   scan.nextLine(); // added this to consume the end of the line that contained
                    // the first number you read

答案 1 :(得分:0)

问题是nextInt()留下了一个新的行字符,它将在第一次迭代中被nextLine()吞噬。所以,你觉得数组大小少了一个。实际上,你的数组的第一个元素,即第0个索引将有一个新的行字符。

您的代码应为:

  System.out.println("How many names do you want to enter?");
   int num = scan.nextInt(); // leaves behind a new line character
   System.out.println("Enter " + num + " Names:");
   String names[] = new String[num];
   scan.nextLine() // to read the new line character left behind by scan.nextInt()