j.doe
j.doe

Reputation: 19

How to print out the correct outputs

To be very brief this is pretty much what I need the code to cast IllegalArgumentException on the forth and last inputs and print out Bad input[]

My most succesfull attempt was to have the code print out Bad input[] after the [2] output and the [1, 2] output.

Current output is

[6, 8, 9, 10]
[1002]
empty array []
[2]
Bad input[]
Bad input[]
[1, 2]

But I need it to be

[6, 8, 9, 10]
[1002]
empty array []
Bad input[]
Bad input[]
Bad input[]
Bad input[]

Entire code below.

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

public class String2intArray {

    public static void main(String[] args) {
        System.out.println(Arrays.toString(str2ia("6,8 ,9 , 10")));
        System.out.println(Arrays.toString(str2ia("1002")));
        System.out.println(Arrays.toString(str2ia("")));
        System.out.println(Arrays.toString(str2ia(", 2")));
        System.out.println(Arrays.toString(str2ia("one,two")));
        System.out.println(Arrays.toString((str2ia("1,,2"))));
        System.out.println(Arrays.toString(str2ia("1 , 2 ,")));  
    }

    public static int[] str2ia(String s) {
        int arraylengt = 0;
        int arrayindex = 0;
        Scanner scan = new Scanner(s).useDelimiter(" *, *");

        if(s.length() == 0) {
            int[] emptyArray = {};
            System.out.print("empty array ");
            return emptyArray;
        }

        while (scan.hasNext()) {
            if (scan.hasNextInt()) {
                int nextInt = scan.nextInt();
                arraylengt ++;
            } else {
                // discard next token
                scan.next(); 
            }
        }

        int[] intArray = new int[arraylengt];

        Scanner scan2 = new Scanner(s).useDelimiter(" *, *");
        try {
            while (scan2.hasNext()) {
                if (scan2.hasNextInt()) {
                    intArray[arrayindex] = scan2.nextInt();
                    arrayindex++; 
                } else {
                    // discard next token
                    throw new IllegalArgumentException("Bad input");
                }    
            }
        } catch (IllegalArgumentException e) {
            System.out.print("Bad input");
            int[] emptyArray = {};
            return emptyArray;
        }

        return intArray;
    }

}

Upvotes: 0

Views: 106

Answers (3)

mallikarjun
mallikarjun

Reputation: 1862

It need a little bit regex than what you have used.

Here is my approach

1) I will compile regex with Pattern (Scanner.useDelimiter internally uses the compiled Pattren)

^\\s*(\\d+(\\s*,\\s*\\d+)*)?\\s*$

2) I will check for matches with the regex on the string.

3) If matches check for empty string, return empty array.

4) if not split string by comma separation and place elements in int array(don't forget to trim the split string)

public static Pattern ARRAY_PATTREN = Pattern
        .compile("^\\s*(\\d+(\\s*,\\s*\\d+)*)?\\s*$");
public static int[] getArray(String str) {

    int[] emptyArray = {};

    Matcher match = ARRAY_PATTREN.matcher(str);

    if (match.matches()) {
        if (str.length() > 0) {
            String[] arr = str.split(",");
            int[] intarray = new int[arr.length];
            for (int i = 0; i < arr.length; i++) {
                intarray[i] = Integer.parseInt(arr[i].trim());
            }
            return intarray;
        }

    } else {
        System.out.print("empty array ");
    }

    return emptyArray;

}

Upvotes: 0

Kevin Cruijssen
Kevin Cruijssen

Reputation: 9326

I would personally do something like this:

Step 1: Remove all whitespaces:

// Remove all spaces from the input:
s = s.replaceAll("\\s", "");

Step 2: Validate if the input is empty. If it is, print and return.

// Is the input empty? Return an empty array
if(s.isEmpty()){
  System.out.print("empty array ");
  int[] emptyArray = {};
  return emptyArray;
}

Step 3: Validate it the input is either a single number, or multiple numbers separated by commas. If it is not, print and return.

// Is the input not valid? Return a bad result
if(!s.matches("(\\d+,)*\\d+")){
  System.out.print("Bad input ");
  int[] emptyArray = {};
  return emptyArray;
}

Step 4: Now we know for sure that the input is valid. So we can split the input by commas (,) and create the integer-array. This can be done with the Scanner you already had, although personally I would use a String[] strArray = s.split(","); and then convert this String-array to an int-array.

With your Scanner it would look like this:

// Determine the length of the array:
int arraylength = 0;
Scanner scan = new Scanner(s).useDelimiter(",");
while(scan.hasNextInt()){
  scan.nextInt(); // Discard the integer
  arraylength++;
}

// Fill the result-array:
int[] intArray = new int[arraylength];
int index = 0;
Scanner scan2 = new Scanner(s).useDelimiter(",");
while(scan2.hasNextInt()){
  intArray[index] = scan2.nextInt();
  index++;
}
return intArray;

Try it online.

For reference, here would be a possible implementation without Scanner:

String[] strArray = s.split(",");
int arrayLength = strArray.length;
int[] intArray = new int[arrayLength];
for(int index = 0; index < arrayLength; index++){
  // No need to try-catch the ParseException, since we already validated the String above
  intArray[index] = Integer.parseInt(strArray[index]);
}
return intArray;

Try it online.

Upvotes: 1

Kathirvel Subramanian
Kathirvel Subramanian

Reputation: 684

Just change .useDelimiter(" *, *") to .useDelimiter(",");

Upvotes: 0

Related Questions