Skip to content Skip to sidebar Skip to footer

Get Int From Text File And Set It To Variable

I'm trying to get the int value of a text file that have text like: 123456789 12345678 1234567 123456 12345 1234 123 12 1 as you can see every number is different and they are in

Solution 1:

This is one way to parse the String to an integer array:

publicint[] toIntArray( String stringFromFile ){

    String[] allStrings = stringFromFile.split( "\\s" );
    int[] intArray = newint[allStrings.length];
    for( int i = 0; i < allStrings.length; ++i ){
        try{
            intArray[i] = Integer.parseInt( allStrings[i] );
        }catch( NumberFormatException e ){
            // Do whatever you think is appropriated
            intArray[i] = -1;
        }
    }
    return intArray;
}

Hope this helps.

Solution 2:

I believe readLine() get you String. You will need to use the Split() method of String and pass in the regularExpression (whitespace).

then you will need to use Integer.parseInt( ) method and pass in every string to parse them into Integer. you also need a loop to do the parse until nothing left

Post a Comment for "Get Int From Text File And Set It To Variable"