代码之家  ›  专栏  ›  技术社区  ›  Teja Nandamuri

接受用户输入后无法打印数组

  •  -2
  • Teja Nandamuri  · 技术社区  · 5 年前

    我在接受键盘输入并将其存储在数组中时遗漏了一些内容。

    我就是这么想的:

        public static void main(String[] args) {
            System.out.println("Hello World");
    
            Scanner obj=new Scanner(System.in);
            System.out.println("enter sentence ");
            String[] inputArray = new String[10];
            int i = 0;
            while (obj.hasNext()){
               String word = (String) obj.next();
               inputArray[i] = word;
               System.out.println("word is  " + word);
               System.out.println("array is  " + inputArray[i]);
    
            }
            System.out.println("final array is  " + inputArray); //This line doesn't print. Why ?
         }
    

    为什么在while循环之后不能打印数组?

    3 回复  |  直到 5 年前
        1
  •  3
  •   Scary Wombat    5 年前

    那是因为你已经在增加 i

    更改为

    String word = (String) obj.next();
    inputArray[i] = word;
    System.out.println("word is  " + word);
    System.out.println("array is  " + inputArray[i]);
    // now increment
    i++;
    

    最后一行没有打印的原因是 obj.hasNext 正在阻塞等待输入,您需要以某种方式断开,也请参见 java Scanner.hasNext() usage

        2
  •  0
  •   Pythus99    5 年前

    你可以使用for循环。

    可能是这样的:

    for(int I; i<inputArray.length;i ++){
    System.out.println("word is  " + word);
    System.out.println("array is  " + inputArray[i]);
    
    }
    
        3
  •  0
  •   Salim    5 年前

    变量“i”在错误的地方递增,所以 System.out.println("array is " + inputArray[I]) 不打印任何值。

    声明 System.out.println("final array is " + inputArray) 没有到达,因为循环从不退出。请参阅下面的代码,我在退出10个条目后退出,并打印最终数组。

        public static void main(String[] args) {
            System.out.println("Hello World");
    
            Scanner obj=new Scanner(System.in);
            System.out.println("enter sentence ");
            String[] inputArray = new String[10];
            int i = 0;
            while (obj.hasNext()){
                if(i >= 10){
                    break;
                }
                String word = (String) obj.next();
                inputArray[i] = word;
                System.out.println("word is  " + word);
                System.out.println("array is  " + inputArray[i]);
                i++; //pls ignore this dumb error
    
            }
            System.out.println("final array is  " + inputArray); //This line doesn't print. Why ?
            Arrays.stream(inputArray).forEach(System.out::println);
        }