I am writing a program where I need to check if a string (name) contains any whitespaces or not.
so there isn't any predefined functions?
Of course, there is - isWhitespace,
plus the trim() method might be considered,
to remove leading and trailing spaces from the user input: name = scanner.next().trim();
boolean containsSpace(String string) {
for (char character : string.toCharArray()) {
if (Character.isWhitespace(character)) {
return true;
}
}
return false;
}
And the second part of your problem - to get the "amount" as a double,
I would split into two simplistic functions to follow single responsibility principle and improve maintainability and testability.
And I will put method getDouble(String string) into a dedicated class, and package, let say: myproject.common.Numbers
So the whole program will consist methods like this:
public static void main(String[] args) {
final var instance = new StackOverflow();
instance.parseNameAndAmount();
}
void parseNameAndAmount() {
Scanner scanner = new Scanner(System.in);
final var name = getName(scanner);
final var amount = getAmount(scanner);
scanner.close();
print("Name is %s".formatted(name));
print("Amount is %s".formatted(amount));
}
String getName(Scanner scanner) {
String name;
do {
print("Enter a name with no spaces: ");
name = getName(scanner.nextLine().trim());
} while (name == null);
return name;
}
String getName(String string) {
if (string == null || string.isEmpty()) {
return null;
}
if (containsSpace(string)) {
return null;
}
return string;
}
boolean containsSpace(String string) {
for (char character : string.toCharArray()) {
if (Character.isWhitespace(character)) {
return true;
}
}
return false;
}
double getAmount(Scanner scanner) {
Double amount;
do {
print("Enter amount of purchase (valid number): ");
amount = getDouble(scanner.nextLine().trim());
} while (amount == null);
return amount;
}
Double getDouble(String string) {
if (string == null) {
return null;
}
try {
return Double.valueOf(string);
} catch (NumberFormatException e) {
return null;
}
}
void print(String string) {
System.out.println(string);
}
As I mentioned testability and maintainability,
one of the tests might look like this, of course to be thorough,
more tests needs to be done.
@Test
void getDouble_When_NegativeWithExponent() {
// Given
final var given = "-12.45E9";
// when
final var actual = stackOverflow.getDouble(given);
// Then
assertThat(actual)
.isNotNull()
.isNegative();
}