StringTokernizer-s-method-countTokens-

Get perfect grades by consistently using our writing services. Place your order and get a quality paper today. Take advantage of our current 20% discount by using the coupon code GET20


Order a Similar Paper Order a Different Paper

Topic

String Tokenizer

Primitive Arrays

Description

Enhance the last assignment by providing the following additional features:

Input All Data As A Single String

Input all data values as a single input string using one input dialog box. Then use a StringTokenizer object to tokenize (separate into components) the data. For this purpose, do the following:

  • Input all data as a single String using JOptionPane.showInputDialog.
  • Create a StringTokenizer object and supply it with the input string and a token delimiter (separator) during object construction.
  • Find the token count by calling StringTokernizer’s method countTokens ( ).
  • Create an array of size count to store data values.
  • Write a Java For statement to loop token count times. During each pass through the loop, obtain the next token by calling StringTokenizer’s nextToken( ) method. Convert the token received as a String to a double and save it in the corresponding array element.

Output All Data To Three Decimal Places

You can display output data to desired number of decimal places. For this purpose do the following:

  • Create a DecimalFormat object and supply it with the appropriate Format String to format decimal numbers to required decimal places.
  • Use the DecimalFormat object to format any decimal numbers into a formatted strings.
  • Display the formatted String.

Testing:

Input Test Run

Test the above program for the input data values below. (User input is shown in bold).

Enter Data <separated by commas/spaces>:

7.2,7.6, 5.1,4.2,2.8,0.9,0.8,0.0,0.4,1.6,3.2,6.4

Enter the Number of Decimal Places to which the Computed Values are displayed :

3

Output Test Run

Original Data: 7.2 7.6 5.1 4.2 2.8 0.9 0.8 0.0 0.4 1.6 3.2 6.4

Sorted Data: 0.0 0.4 0.8 0.9 1.6 2.8 3.2 4.2 5.1 6.4 7.2 7.6

Computed Values Displayed To 3 Decimal Places:

Min Value: 0.000

Max Value: 7.600

Mean: 3.350

Median: 3.000

Discussion

Input All Data As a Single String

/*

You can input all data as a single string and then tokenize it using a StringTokenizer object.

The StringTokenizer class is available in java.util package.

The sample code is provided below which does the following:

  • It inputs decimal numbers as a String separated by commas/spaces.
  • It tokenizes the input String i.e. it separates them into tokens one at a time.
  • It converts each token received (as String) into a double and stores it in the corresponding array data element.

*/

Sample Code (Using For Loop)

import java.util.*;

//Create a String in for inputting data values.

String in=””;

//Create a String delim for specifying the delimiter (separator).

String delim = “, “;

//Create an int count to get token count from StringTokenizer.

int count=0;

//Create a String token to get token value from the StringTokenizer.

token=””;

//Get user input in String in

in = JOptionPane.showInputDialog

(“Enter data values separated by spaces and/or commas”);

//Create StringTokenizer and supply it with String in and String delim

StringTokenizer st = new StringTokenizer (in, delim);

//Get token count from StringTokenizer

count = st.countTokens ( );

//Create an array data of size count.

double [ ] data = new double [count];

//Set up a for loop to go arount count times.

//In each pass through the loop, get the next token from StringTokenizer.

//Convert token into a double and store it in corresponding array element.

for (int i=0; i<count; i++)

{

token = st.nextToken ( );

//trim the token

//trim removes all leading and trailing spaces.

token = token.trim ( );

data [i] = Double.parseDouble(token);

}

Sample Code (Using While loop)

//Create a String in for inputting data values.

String in=””;

//Create a String delim for specifying the delimiter (separator).

String delim = “, “;

//Create an int count to get data count from user.

int count=0;

//Create a String token to get token value from the StringTokenizer.

token=””;

//Get data count from user

in = JOptionPane.showInputDialog

(“Enter the total number of data values”);

count = Integer.parseInt ( in );

//Create an array data of size count.

double [ ] data = new double [count];

//Get data input in String in

in = JOptionPane.showInputDialog

(“Enter data values separated by spaces and/or commas”);

//Create StringTokenizer and supply it with String in and String delim

StringTokenizer st = new StringTokenizer (in, delim);

//Set up a while loop to go around till you fill the array or run out of tokens.

//In each pass through the loop, get the next token from StringTokenizer.

//Convert token into a double and store it in corresponding array element.

int i = 0;

while (tk.hasMoreToken ( ) && i<data.length)

{

token = tk.nextToken ( );

//trim the token

//trim removes all leading and trailing spaces.

token = token.trim ( );

data [i] = Double.parseDouble (token);

i++;

}

//If the number of data values provided is less than expected,

//display an error message and exit.

if ( i < data.length )

{

//display error and exit

JOptionPane.showMessageDialog

(“Insufficient data values provided”);

System.exit ( 0 );

}

Handling Mixture Of Commas And Spaces In Input

//use comma as a delimiter as below:

String delim = “, “;

//after reading the token, trim it.

//trim removes all leading spaces (spaces in the beginning of a String)

//and all trailing spaces (spaces at the end of a String).

token = token.trim ( );

Formating A Deciamal Number:

The sample code below formats the variable double n to two decimal places using two different methods.

Method I

import java.text.*;

//Input the number of decimal places

String in = JOptionPane.showInputDialog(“Enter the Number of Places For Decimal Output”);

int placesCount = Integer.parseInt (in);

//Build pattern string

String pattern = “.0”;

for (int i=0; i<placesCount; i++)

pattern = pattern + “0”;

//Create a DecimalFormat object. Pass it the pattern string.

DecimalFormat df = new DecimalFormat ( pattern);

//Call format method of DecimalFormat object to convert a double into formatted string.

double min = 99.999999;

String out = “Min: “ + df.format (min) + “n”;

JOptionPane.showMessageDialog (null, out);

Method 2:

import java.text.*;

//Input the number of decimal places

String in = JOptionPane.showInputDialog(“Enter the Number of Places For Decimal Output”);

int placesCount = Integer.parseInt (in);

//Build pattern string

String pattern = “.0”;

for (int i=0; i<placesCount; i++)

pattern = pattern + “0”;

//Create a DecimalFormat object. Pass it the pattern string.

DecimalFormat df = new DecimalFormat ( );

//use applyPattern

df.applyPattern (pattern);

//Call format method of DecimalFormat object to convert a double into formatted string.

double min = 99.999999;

String out = “Min: “ + df.format (min) + “n”;

JOptionPane.showMessageDialog (null, out);

Pattern “0.000”:

DecimalFormat df = new DecimalFormat ( “0.000”);

The df object above will format with the following provisions:

Format result to 3 decimal places.

Zero fill any of the missing number in the 3 decimal places.

Format the whole number part such as to display at least one digit.

Zero fill the least significant digit of the whole number part if it is missing.

Patterns:

In the formatting pattern,

0 indicate a required digit position. If there is no digit available, the position is zero filled.

# indicates an optional digit position, If there is no digit available, the position is left unfilled.

The position is not zero filled.

The example patterns below demonstrate the usage of 0 and #.

.000 Must display three and only three decimal digits.

If result has less than three digits, zero fill to make three digits.

If the result has more than three digits, display only three digits.

.### Display up to three decimal digits.

If the answer has less than three digits, display the available number of digits.

Don’t zero fill the unavailable digits.

If answer has more than three digits, display three digits.

####.000 Display 4 digits before the decimal point.

If less than 4 digits, display the available digits. Don’t zero fill the unavailable digits.

If more than 4 digits, display all. This is done to make sure that the whole number part is not changed.

Got stuck with another paper? We can help! Use our paper writing service to score better grades and meet your deadlines.

Get 15% discount for your first order


Order a Similar Paper Order a Different Paper
Writerbay.net