为什么此代码不等待用户输入?

时间:2018-02-08 22:25:28

标签: java

我刚刚在java中编写了一些代码,它应该让用户逐位输入数据。捕获所有数据后,它将执行其操作并丢弃一些输出。现在问题是:程序根本不等待用户输入。这是我的代码的最小化版本:

import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
public class MyClass {
    // initialize array variable in global namespace
    static boolean[][] array;
    public static void main(String[] args) {
        // Input numbers
        Scanner text = new Scanner(System.in);
        int[] first_in = new int[2];

        System.out.println("Please start data entry: \n");
        // Take in first variables (numbers)
        for(int i = 0; i<first_in[0]; i++) {
            first_in[i] = text.nextInt();
        }
        int n = first_in[0];

        // Initialize reference array
        String[] reference = new String[n];
        System.out.println("Please give names: \n");
        // Ask for reference names
        for(int i = 0; i<n; i++) {
            reference[i] = text.next();
        }

        System.out.println("Please give other data: \n");
        // Ask for edges
        String edgein;
        for(int i = 0; i<first_in[1]; i++) {
            edgein = text.nextLine();
            /* do some stuff */
        }
        // Be nice and close the scanner
        text.close();
        System.out.println("Scanner closed.");

输出只是

Please start data entry: 

Please give vertices: 

Please give edges: 

Scanner closed.

为什么程序不会在三个循环中的任何一个循环中等待用户输入?我该如何解决?

1 个答案:

答案 0 :(得分:2)

您需要初始化数组first_in。默认值为[0,0],因此它不会进入循环,因为比较i<first_in[0]将为0<0

    Scanner text = new Scanner(System.in);
    int[] first_in = new int[2];

    System.out.println("Please start data entry: \n");
    // Take in first variables (numbers)
    for(int i = 0; i<first_in[0]; i++) {
        first_in[i] = text.nextInt();
    }
    int n = first_in[0];