-1

I'm going through a coding question. An array is monotonic if it is either monotone increasing or monotone decreasing. if it is, then print true. e.g Input: [1,2,2,3] Output: true

Input: [6,5,4,4] Output: true

Input: [1,3,2] Output: false

Now, problem is how to handle this input using Scanner? Do I need to take it as String and then remove with some tricks or there is better way to take input like above?

I saw a result here in C++

but it does not helped me. How can I do it. Any help is appreciated.

Note: I do not need the solved code for this problem. Rather i'm interested in how to take above array as input.

Jabongg
  • 2,099
  • 2
  • 15
  • 32
  • Ask the user for array size. Create array of that size. Read each int and add to array. – 001 Sep 05 '18 at 17:31
  • 2
    If a coding question says "Input: [6,5,4,4]" it conventionally means "Given an input array with elements 6, 5, 4 and 4..". It does not mean you're supposed to read the string on the format `"[6,5,4,4]"` from stdin and parse it into an array. – that other guy Sep 05 '18 at 17:31
  • ok, then it simply i need to take it as string and then use split and remove the brackets, and then go smooth with the extracted integer array. right? – Jabongg Sep 05 '18 at 17:33
  • It means you're supposed to write a method `boolean isMonotonic(int[] array) { ...; }` that does not use Scanner. – that other guy Sep 05 '18 at 17:35
  • actually here it is, a sample problem from leetcode.. https://leetcode.com/contest/weekly-contest-100/problems/monotonic-array/ thats why I was asking. – Jabongg Sep 05 '18 at 17:37
  • Yes, you are right @thatotherguy – Jabongg Sep 05 '18 at 17:38
  • Here's an example: https://ideone.com/7B0qHQ – 001 Sep 05 '18 at 17:43

1 Answers1

1

The code below will take the following format of input: [1,2,3,4,5,6] and it will save it to an array of integers.

    Scanner scanner = new Scanner(System.in);
    int[] a = Arrays.stream(scanner.next().split("[,\\[\\]]")).filter(w -> !w.equals("")).mapToInt(Integer::parseInt).toArray();

    for (int i = 0; i < a.length; i++) {
        System.out.println(a[i]);
    }

Import:

import java.util.Arrays;
import java.util.Scanner;