Reputation: 127
In my code, I want the loop to exit if the user enters an empty string for either variables. Nothing seems to work after I enter an empty string.
Where am I going wrong?
import java.util.HashMap;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String lakeName;
String timeRun;
HashMap<String, Double> newMap = new HashMap<>();
do {
System.out.println("Enter the Lake Name");
lakeName = input.nextLine();
System.out.println("Enter number of minutes run");
timeRun = input.nextLine();
Double finalRun = Double.parseDouble(timeRun);
newMap.put(lakeName, finalRun);
if(lakeName.equalsIgnoreCase("") || timeRun.equalsIgnoreCase("")){
break;
}
} while(true);
for(String key: newMap.keySet()){
Double value = newMap.get(key);
System.out.println(key + ": "+ value);
}
}
}
Upvotes: 1
Views: 45
Reputation: 4620
When you enter an empty string for the timeRun
, you will try to parse an empty string as double. This fails and throws this exception:
java.lang.NumberFormatException: empty String
You can solve this by placing the following code into the loop:
System.out.println("Enter the Lake Name");
lakeName = input.nextLine();
System.out.println("Enter number of minutes run");
timeRun = input.nextLine();
if (lakeName.equalsIgnoreCase("") || timeRun.equalsIgnoreCase("")) {
break;
}
Double finalRun = Double.parseDouble(timeRun);
newMap.put(lakeName, finalRun);
I just moved the break
up a few lines, including its condition.
Also, you can replace the .equalsIgnoreCase("")
by .isEmpty()
, as already stated in the other answer.
Upvotes: 2
Reputation: 176
try this :
do {
System.out.println("Enter the Lake Name");
lakeName = input.nextLine();
System.out.println("Enter number of minutes run");
timeRun = input.nextLine();
if(lakeName.equalsIgnoreCase("") || timeRun.equalsIgnoreCase("")){
break;
}
Double finalRun = Double.parseDouble(timeRun);
newMap.put(lakeName, finalRun);
} while(true);
put the if{...}
up, if not , it will be given NumberFormatException.
Upvotes: 3