(This program project comes from Chapter 11: Exceptions and Input/Output Operati
ID: 3671039 • Letter: #
Question
(This program project comes from Chapter 11: Exceptions and Input/Output Operations in the book Java Illuminated)
Design a class that checks if a String is made of tokens of the same data type (for this, you may only consider four data types: boolean, int, double , or char ). This class has two instance variables: the String of data and its delimiter. Other than the constructor, you should include a method, checkTokens, that takes one parameter, representing the data type expected (for example, 0 could represent boolean , 1 could represent int , 2 could represent double , and 3 could represent char ). The method returns true if all the tokens in the String are of the specified data type; otherwise, it returns false.
Explanation / Answer
import java.util.Scanner;
public class StrToken {
private String data;
private String delimeter;
public StrToken(String data, String delimeter) {
this.data = data;
this.delimeter = delimeter;
}
public boolean checkTokens(int type) {
String dataToken[] = data.split(delimeter);
// boolean
if (type == 0) {
for (String st : dataToken) {
{
if (!("true".equalsIgnoreCase(st) || "false"
.equalsIgnoreCase(st))) {
return false;
}
}
}
} else if (type == 1) {
for (String st : dataToken) {
try {
Integer.parseInt(st);
} catch (Exception e) {
return false;
}
}
} else if (type == 2) {
for (String st : dataToken) {
try {
Double.parseDouble(st);
if (!st.contains(".")) {
return false;
}
} catch (Exception e) {
return false;
}
}
} else if (type == 3) {
for (String st : dataToken) {
if (st.length() > 1) {
return false;
}
if (!Character.isLetter(st.charAt(0))) {
return false;
}
}
}
return true;
}
public static void main(String[] args) {
StrToken s = new StrToken("121.3,322.3", ",");
System.out.println(s.checkTokens(2));
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.