【问题标题】:How can i alternate this input?我怎样才能交替这个输入?
【发布时间】:2015-02-07 20:28:12
【问题描述】:

我在使用这个 Java 输入时遇到了一些问题:

public class Testinput {
    public static void main(String[] args) {
        int N = StdIn.readInt();
        String[] name = new String[N];
        int[] year = new int[N];
        for (int i = 0; i < name.length; i++) {
            name[i] = StdIn.readString();
            for (int j = 0; j < name.length; j++) {
                year[j] = StdIn.readInt();
            }
        }
        for (int i = 0; i < name.length; i++ ) {
            System.out.println(name[i]+" " +year[i]);
        }
    }
}

例如:需要交替读取姓名和年龄:

2
bob
1963
kelly
1981

并打印:

bob 1963
kelly 1961

但它要求输入长度为 6(而不是 2*N = 4)并打印出来:

input1 input5
input4 input6

你们能帮我解决这个问题吗?

【问题讨论】:

  • 您只需要一个for 循环即可。在该循环内读取两个元素 name[i]year[i]

标签: java stdin


【解决方案1】:

您是否来自习惯于 Char-array 的 C 背景?在 Java 中,这非常简单。可以通过字符串输入。

Scanner scn = new Scanner(System.in); //Create a scanner object

int n = scn.nextInt();           //Enter number of people you want to prompt and record
String[] name = new String[n];   //Create array of size based on n
int[] year = new int[n];         //Create array of size based on n

for(int x=0; x<n; x++){
    name[x] = scn.nextLine();    //for string inputs
    year[x] = scn.nextInt();     //for whole number
}

这将为您提供输入的替代方案。 我遇到的大多数大学和学校都教他们的学生使用扫描仪来接收用户输入。因此,如果允许,您可能也想使用它。

【讨论】:

    猜你喜欢
    • 2021-09-24
    • 2022-11-01
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    相关资源
    最近更新 更多