Reading multiple Scanner inputs

后端 未结 1 790
粉色の甜心
粉色の甜心 2020-12-09 22:24

What I am trying to do is have multiple inputs that all have different variables. Each variable will be part of different equations. I am looking for a way to do this and, I

相关标签:
1条回答
  • 2020-12-09 23:04

    If every input asks the same question, you should use a for loop and an array of inputs:

    Scanner dd = new Scanner(System.in);
    int[] vars = new int[3];
    
    for(int i = 0; i < vars.length; i++) {
      System.out.println("Enter next var: ");
      vars[i] = dd.nextInt();
    }
    

    Or as Chip suggested, you can parse the input from one line:

    Scanner in = new Scanner(System.in);
    int[] vars = new int[3];
    
    System.out.println("Enter "+vars.length+" vars: ");
    for(int i = 0; i < vars.length; i++)
      vars[i] = in.nextInt();
    

    You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.

    0 讨论(0)
提交回复
热议问题