方法用数组输出两次

时间:2014-12-03 12:23:20

标签: java arrays methods

我必须基本上创建一个程序,在给定提示的情况下添加名称并将其放在数组中。对于这个人的年龄,它应该做同样的事情。我被迫用方法做到这一点。我遇到的唯一问题是,在第3行的最后一行,名字被问了两次。我不知道如何解决这个问题。任何帮助表示赞赏。

public class Testing1 {
public static int[] ageinput(String names[], int q2){
    int holderage[] = new int[q2];
    for(int x = 0; x<q2;x++) {``
        System.out.println("Please input the age of " + names[x]);
        Scanner age = new Scanner(System.in);
        int a1 = age.nextInt();
        holderage[x] = a1;
    }
    return holderage;
}
public static String[] nameinput(int q2){
    String holdername[] = new String[q2];
    for (int x = 0; x<q2;x++) {
        System.out.println("Please input the name of the person");
        Scanner name = new Scanner(System.in);
        String n1 = name.nextLine();
        holdername[x]=n1;
    }
    return holdername;

}
public static void output(String names[], int ages[]){
    for(int x = 0; x<names.length;x++){
        System.out.println(names[x]+" is "+ages[x]+" years old");
    }
}
public static void main(String[] args) {
    System.out.println("How many names do you want to input?");
    Scanner question = new Scanner(System.in);
    int q1 = question.nextInt();
    output(nameinput(q1),ageinput(nameinput(q1),q1));
}

}

2 个答案:

答案 0 :(得分:0)

output(nameinput(q1),ageinput(nameinput(q1),q1));中,您调用方法nameinput两次,因此代码也会执行两次。 您可以询问nameinput中的名称,将它们存储到数组中并将该数组传递给ageinput

答案 1 :(得分:0)

@Aadithya Gowthaman,在你的编辑器中尝试这个。

package com.aamir;

import java.util.Scanner;

public class Testing1 {
public static int[] ageinput(String names[], int q2){
int holderage[] = new int[q2];
for(int x = 0; x<q2;x++) {
    System.out.println("Please input the age of " + names[x]);
    Scanner age = new Scanner(System.in);
    int a1 = age.nextInt();
    holderage[x] = a1;
}
return holderage;
}
public static String[] nameinput(int q2){
    String holdername[] = new String[q2];
    for (int x = 0; x<q2;x++) {
    System.out.println("Please input the name of the person");
    Scanner name = new Scanner(System.in);
    String n1 = name.nextLine();
    holdername[x]=n1;
}
return holdername;

}
public static void output(String names[], int ages[]){
for(int x = 0; x<names.length;x++){
    System.out.println(names[x]+" is "+ages[x]+" years old");
}
}
public static void main(String[] args) {
System.out.println("How many names do you want to input?");
Scanner question = new Scanner(System.in);
int q1 = question.nextInt();
String [] namesArray =  nameinput(q1);
int [] ageArray =  ageinput(namesArray, q1);

output(namesArray, ageArray);
}
}