数组java中用户输入的输出值

时间:2014-08-19 07:55:41

标签: java arrays

我正在制作一个用户输入用户想要的输入数量的程序。例如,如果用户输入3,则会出现3个用户输入。这个程序的输出是这样的:

    ----------------------------------
    Enter How Many Inputs: 3

    enter name:
    rendell //value to be outputted

    enter age:
    20 //value to be outputted

    enter gender:
    male //value to be outputted
    -----------------------------------     

现在,我希望将输入的值存储在某个地方,然后单独输出,但我不知道该怎么做。我试图使用ctr1变量,但它只输出最后一个用户输入的值。

这是我的代码:

    Object stud1 [][] = {{1,2,3},{"enter name:","enter age:","enter gender:"}};
    String ctr1;

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    Scanner scan = new Scanner(System.in);


    System.out.print("Enter How Many Inputs: ");
    int num1 = Integer.parseInt(in.readLine());

    for (int i = 0; i<num1;i++){
         System.out.println(pers[1][i]);
         ctr1 = in.readLine();
            }

1 个答案:

答案 0 :(得分:1)

问题是你只是将一个引用中的所有输入分配给String,因此你可以打印用户刚给出的所有输入。

<强>溶液

如果用户

,您可以使用String数组来输入输入数据中的所有值

<强>样品:

    String [] choices = { "enter name:","enter age:","enter gender:"};
    String ctr1[];

    Scanner scan = new Scanner(System.in);
    System.out.print("Enter How Many Inputs: ");
    int num1 = Integer.parseInt(scan.nextLine());
    ctr1 = new String[num1];

    for (int i = 0; i < num1; i++) {
        System.out.println(choices[i]);
        ctr1[i] = scan.nextLine();
    }

    for(int i = 0; i < ctr1.length; i++)
    {
        if(i == 0)
            System.out.println("Name: "+ ctr1[i]);
        else if( i == 1)
            System.out.println("Age: "+ ctr1[i]);
        else if( i == 2)
            System.out.println("Gender: "+ ctr1[i]);
    }

<强>结果:

Enter How Many Inputs: 3
enter name:
Rod_algonquin
enter age:
12
enter gender:
male
Name: Rod_algonquin
Age: 12
Gender: male