2

I'm doing old codeforces problems for practice, and a pattern I repeat often in Python is:

(m, n, k) = [int(i) for i in raw_input().split()]

to quickly assign m, n, k because inputs such as

4 2 7

are common in codeforces as a first input line. Is there any way I can do this kind of thing (with multiple variables m, n, k) quickly in Java (preferably 1-2 liner)?

Any help appreciated (or link to somewhere that answers the q). Thanks!

1
  • 1
    No, you have to write three separate statements for this. Commented Aug 8, 2015 at 2:21

2 Answers 2

2

The quickest way I can think of is like so:

    System.out.println("Enter values:");
    Scanner scan = new Scanner(System.in);
    int i = scan.nextInt();
    int j = scan.nextInt();
    int k = scan.nextInt();
    System.out.print(i + " " + j + " " + k);

Input: 1 2 3

Output: 1 2 3

Sign up to request clarification or add additional context in comments.

Comments

1

This may not be exactly what you're wanting, IMO, it's a close substitute if you store the input in an array. You don't have three "separate" variables per say, but a 1 - 2 liner as you're requesting.

public static void main(String[] args) throws Exception {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter 3 values separated by spaces: ");
    int[] mnk = Arrays.stream(input.nextLine().split(" "))
            .mapToInt(a -> Integer.parseInt(a)).toArray();
    System.out.println(Arrays.toString(mnk));
}

The other "downside" to a method like this, is that the input is SO restrictive to integers being entered and separated by spaces. There is no way you're going to get a 1 - 2 liner with error checking.

Results:

Enter 3 values separated by spaces: 4 2 7
[4, 2, 7]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.