Java – read multiple scanner inputs

What I want to do is have multiple inputs with different variables Each variable is part of a different equation I'm looking for a way to do this, and I think I have an idea I just want to know if it's legal and if there's a better way to do it

import java.util.*;

public class Example{

public static void main(String args[]){

    Scanner dd = new Scanner(system.in);

    System.out.println("Enter number.");
    int a = dd.nextInt();
    System.out.println("Enter number.");
    int b = dd.nextInt();
    System.out.println("Enter number.");
    int c = dd.nextInt();
  }
}

Solution

If each input asks the same question, use the for loop and the input array:

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 suggests, 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're on the right track. What work have you done It's just a better, more flexible way of doing things

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>