Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading multiple Scanner inputs

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();
  }
}
like image 824
John Avatar asked Dec 12 '11 04:12

John


People also ask

How do I scan multiple values in Java?

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.

How do you scan two inputs in one line in Java?

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.

Can we use multiple scanners in Java?

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..


1 Answers

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.

like image 67
Jon Egeland Avatar answered Oct 09 '22 12:10

Jon Egeland