0

I am trying to get multiple inputs in a single code of line.. for example in c++, we could have it like -

int a,b,c;
cin>>a>>b>>c;

is it possible in java also??

hitain09
  • 19
  • 2
  • I can't believe you haven't googled something like "java assign multiple variables simultaneously" - the first 8 results are all stack overflow! :) – Caius Jard Jul 25 '17 at 06:09
  • 3
    Possible duplicate of [Java - assigning two expressions to a single variable simultaneously](https://stackoverflow.com/questions/3996593/java-assigning-two-expressions-to-a-single-variable-simultaneously) – Caius Jard Jul 25 '17 at 06:11
  • Possible duplicate of [How to print multiple variable lines in java](https://stackoverflow.com/questions/23584563/how-to-print-multiple-variable-lines-in-java) – Jozef Dúc Jul 25 '17 at 07:09
  • For those of use who know Java, but not C++, you might want to add an explanation of exactly what that code does: does it read one value and assign it to all 3, or does it read three values? – Mark Rotteveel Jul 25 '17 at 19:50

1 Answers1

1

You can use an array for this purpose, like:

public static void main(String[] args) {
        int[] values = new int[3];
        Scanner in = new Scanner(System.in);
        for(int i = 0; i < values.length; i++) {
            values[i] = in.nextInt();
        }
        System.out.println(Arrays.toString(values));
    }

UPDATE 2

In java 8 the above solution can have a shorter version:

Scanner in = new Scanner(System.in);
Integer[] inputs = Stream.generate(in::nextInt).limit(3).toArray(Integer[]::new);

UPDATE 1

There is another way, which is closer to cin:

public class ChainScanner {
        private Scanner scanner;

        public ChainScanner(Scanner scanner) {
            this.scanner = scanner;
        }

        public ChainScanner readIntTo(Consumer<Integer> consumer) {
            consumer.accept(scanner.nextInt());
            return this;
        }

        public ChainScanner readStringTo(Consumer<String> consumer) {
            consumer.accept(scanner.next());
            return this;
        }
    }

    public class Wrapper {
        private int a;
        private int b;
        private String c;

        public void setA(int a) {
            this.a = a;
        } /* ... */
    }

    public static void main(String[] args) {
        ChainScanner cs = new ChainScanner(new Scanner(System.in));
        Wrapper wrapper = new Wrapper();

        cs.readIntTo(wrapper::setA).readIntTo(wrapper::setB).readStringTo(wrapper::setC);

        System.out.println(wrapper);
    }
Adrian
  • 2,984
  • 15
  • 27
  • but if want characters between integers, examples in c++ - int m,n; char c; cin>>m>>c>>n; – hitain09 Jul 25 '17 at 11:57
  • @hitain09 a solution would be to make `values` of `String[]` type, read from input with `in.next()` and then make conversion, for example, `Integer.valueOf(values[1])` – Adrian Jul 25 '17 at 12:17