I am unsure on how to do this following method in Java. I have posted the follow
ID: 3700868 • Letter: I
Question
I am unsure on how to do this following method in Java. I have posted the following instructions given on the javadoc.
/** * 10 marks
* assume that base has already been set (to a value between 2 and 10).
* populate array data with the contents of String passed such that any invalid
* characters (outside the range ['0', character corresponding to (base-1)] are
* ignored.
*
* if none of the characters in the String passed are valid symbols for the number system,
* set data to an array containing 0, that is the array {0}.
*
* For example, * if base = 4 and d = "341518", data becomes {3,1,1}
* if base = 9 and d = "341518", data becomes {3,4,1,5,1,8}
* if base = 4 and d = "9sh2883^1", data becomes {2,3,1}
* @param d
*/
public void setDataAdvanced(String d) {
setBase(2); //to be completed;
data = new int[] {0}; //to be completed
}
Explanation / Answer
/** * 10 marks
* assume that base has already been set (to a value between 2 and 10).
* populate array data with the contents of String passed such that any invalid
* characters (outside the range ['0', character corresponding to (base-1)] are
* ignored.
*
* if none of the characters in the String passed are valid symbols for the number system,
* set data to an array containing 0, that is the array {0}.
*
* For example, * if base = 4 and d = "341518", data becomes {3,1,1}
* if base = 9 and d = "341518", data becomes {3,4,1,5,1,8}
* if base = 4 and d = "9sh2883^1", data becomes {2,3,1}
* @param d
*/
public void setDataAdvanced(String d)
{
//setBase(2); //to be completed;
//data = new int[] {0}; //to be completed
// store the number of characters which are valid
int count = 0;
int i;
// get the number of characters which are valid
for( i = 0 ; i < d.length() ; i++ )
{
// if the current character is digit
// get i th character using charAt(i)
// isDigit() return true if the character is digit
// convert character to int using Integer.parseInt()
if( d.charAt(i).isDigit() == true && Integer.parseInt( d.charAt(i) ) < base )
count++;
}
// if no character is valid
if( count == 0 )
data = new int[1];
else
{
// create array of size count
data = new int[count];
int index = 0;
// fill data with characters which are valid
for( i = 0 ; i < d.length() ; i++ )
{
// if the current character is digit
// get i th character using charAt(i)
// isDigit() return true if the character is digit
// convert character to int using Integer.parseInt()
if( d.charAt(i).isDigit() == true && Integer.parseInt( d.charAt(i) ) < base )
{
// convert character to int using Integer.parseInt() and
// add it to data
data[index] = Integer.parseInt( d.charAt(i) );
index++;
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.