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 think I have an idea. I just want to know if this would be legal and, if maybe there is a better way to do this.
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();
}
}
This question is related to
java
java.util.scanner
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.
Source: Stackoverflow.com