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();
}
}
For example, if want to take input a string or multiple string, we use naxtLine() method. It is only a way to take multiple string input in Java using the nextLine() method of the Scanner class.
To do this, we could read in the user's input String by wrapping an InputStreamReader object in a BufferedReader object. Then, we use the readLine() method of the BufferedReader to read the input String – say, two integers separated by a space character. These can be parsed into two separate Strings using the String.
You can create only one scanner object and use it any where else in this class. Why you need multiple Scanner? You can do with only one..
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With