I would like to prevent user from includingSpace
in a String
input.
I have tried using a few methods such as:
(team1Name.contains(" "))
(team1Name.matches(".*([ \t]).*"))
(team1Name.indexOf(' ') >= 0)
but to no avail.
Below is a a snippet of my code and the output:
Code snippet:
System.out.print("Name of Team 1: ");
team1Name = sc.next();
if (team1Name.indexOf(' ') >= 0) {
System.err.println("Error");
System.out.print("Name of Team 1: ");
team1Name = sc.next();
}
System.out.print(team1Name+ " Goals: ");
while (true) {
try {
team1Goals = Integer.parseInt(sc.next());
break;
} catch (NumberFormatException nfe) {
System.err.println("Error");
System.out.print(team1Name+ " Goals: ");
}
}
Output:
Name of Team 1: black sheep
Error
black Goals: black Goals:
UPDATE:
Attempt to use .nextLine()
instead of .next()
. However, still receive error output:
Name of Team 1: black sheep
Error
Error
[] Goals: [] Goals:
Placed []
to replace the original Space
/empty
output