Axel Finkel Axel Finkel - 1 month ago 10
Java Question

How to read in and split a string of numbers separated by whitespace and forward slash

Sample input: 1/2 3/4 5/6 7/8 9/10

What I expect it to do: first split the string based on whitespace, so you end up with a string array of {1/2 , 3/4 , 5/6 , 6/8 , 9/10}, and then split that into an array of integers intA{1,2}, intB{3,4}, intC{5,6}, intD{7,8}, intE{9,10} so that I can finally pass them into a fraction object with a numerator and denominator.

Here is what I currently have:

public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
String str;
str = keyboard.nextLine();
String[] splitStr = str.split(" ");

Fraction[] input = new Fraction[10];

for(int i = 0; i < splitStr.length; i++)
{
String[] fract = splitStr[i].split("/");
int num = Integer.valueOf(fract[0]);
int den = Integer.valueOf(fract[1]);
double fraction = (double)num / den;
}

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


When I input the above string, I get null values back. If I enter any values without a forward slash, like so:
1/2 3/4 5/6 7 8 9/10
instead of reading the 7 and 8 as 7/1 and 8/1 the program runs into a NullPointerException error. There has got to be an easier way to do this, isn't there?

Answer

I get null values back

That is because you don't add any values to the input, you only initalize it which will fill it with null values.

I'm not sure how you create Fraction objects but you need to create this kind of objects and add them to the array. Here is an example:

Fraction[] input = new Fraction[10];

for(int i = 0; i < splitStr.length; i++) {
    String[] fract = splitStr[i].split("/");
    int num = Integer.valueOf(fract[0]);
    int den = Integer.valueOf(fract[1]);
    input[i] = new Fraction(num, den);
}

If you want to set the denominator to 1 when the input contains single numbers, you can do something like this:

for(int i = 0; i < splitStr.length; i++) {
    String[] fract = splitStr[i].split("/");
    int num = Integer.valueOf(fract[0]);
    int den = 1;
    if(fract.length == 2){
        den = Integer.valueOf(fract[1]);
    }
    input[i] = new Fraction(num, den);
}

Also, it is safer to set the input array's length to be equal to the splitStr array's length.

Fraction[] input = new Fraction[splitStr.length];