用户输入名称的年龄

时间:2016-10-24 07:40:56

标签: java for-loop

所以我需要做以下事情: 当用户在控制台中键入他们的名字然后被提示填写他们的年龄,之后需要显示他们年龄的数量的名称。所以举个例子 用户输入是Mikey 年龄输入是:4 控制台打印:
米奇
米奇
米奇
Mikey

到目前为止,我制作了以下代码:

 public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String invoer;
        String invoer2;
        System.out.print("Fill in your name:");
        invoer = br.readLine();
        System.out.print("Fill in your age:");
        invoer2 = br.readLine();
        System.out.print("" + invoer);
        System.out.print(" " + invoer2);
    }

我是java的新手,所以我不确定问题是什么,修复可能是什么。我一直在寻找这样的代码,看看我做错了什么,但我似乎找不到。

2 个答案:

答案 0 :(得分:1)

 public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String invoer;
    String invoer2;
    System.out.print("Fill in your name:");
    invoer = br.readLine();
    System.out.print("Fill in your age:");
    invoer2 = br.readLine();
    try {
        for (int i = 0; i < Integer.parseInt(invoer2); i++) {
            System.out.println(invoer);
        }
    } catch (NumberFormatException e) {
        System.out.println("Age should be a number");
        e.printStackTrace();
    }
    System.out.print("" + invoer);
    System.out.print(" " + invoer2);
}

您已从用户输入中获取号码。这可以使用Integer.parseInt(invoer2)完成。但是,如果输入不是有效数字,它可以抛出NumberFormatException

但我建议使用Scanner

 public static void main(String[] args) throws IOException {
    Scanner s = new Scanner(System.in);
    String invoer;
    String invoer2;
    System.out.print("Fill in your name:");
    invoer = s.next();
    System.out.print("Fill in your age:");
    try {
        invoer2 = s.nextInt();
        for (int i = 0; i < invoer2; i++) {
            System.out.println(invoer);
        }
    } catch (InputMismatchException e) {
        System.out.println("It wasn't valid age");
    }
    System.out.print("" + invoer);
    System.out.print(" " + invoer2);
}

答案 1 :(得分:0)

您需要使用循环为每个年份打印一次名称。但首先,将年龄的字符串输入转换为int,然后可以将其用作循环的边界。

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String invoer;
    int invoer2;
    System.out.print("Fill in your name:");
    invoer = br.readLine();
    System.out.print("Fill in your age:");
    invoer2 = Integer.parseInt(br.readLine());
    for (int i=0; i < invoer2; ++i) {
        System.out.print(invoer);
    }
}