I’m writing a program that assists Mars settlers in calculating the area/size of their potential house. The whole first half of the program works as intended, but for some reason when I prompt the user if they would like to input a second house, my scanner doesn’t accept any more input and the program execution ends, not allowing me to type in yes or no as a response, it just prints out the user prompt and cuts off. What am I doing wrong here?
import java.util.Scanner;
public class MartianHouses{
public static void main(String[] args){
/*Set up scanner & declare variables*/
Scanner sc = new Scanner(System.in);
double sqFt = 14.5;
/*Receive input from user*/
System.out.println("Enter the settler's name: ");
String name = sc.nextLine();
System.out.println("Enter the length of a side of the house: ");
double s = sc.nextDouble();
/*Calculate area of floor&roof*/
double floorArea = 2*s*s*(1 + Math.sqrt(2));
/*Calculate walls area*/
double wallsArea = 8 * 12 * s;
/*Calculate total area*/
double totArea = (floorArea * 2) + wallsArea;
/*Calculate floor cost*/
double totCost = totArea * sqFt;
/*Print results*/
System.out.print(name + " has a house surface area of ");
System.out.printf("%,.2f", totArea);
System.out.print(" and a cost of $");
System.out.printf("%,.2f", totCost);
System.out.print(".");
System.out.println(" Would you like to enter another house? Enter no to exit.");
String response = sc.nextLine();
double sqFt2 = 14.5;
switch(response.toLowerCase()) {
case "yes" :
System.out.println("Enter the settler's name: ");
String name2 = sc.nextLine();
System.out.println("Enter the length of a side of the house: ");
double s2 = sc.nextDouble();
double floorArea2 = 2*s2*s2*(1 + Math.sqrt(2));
double wallsArea2 = 8 * 12 * s2;
double totArea2 = (floorArea2 * 2) + wallsArea2;
double totCost2 = totArea2 * sqFt2;
System.out.print(name2 + " has a house surface area of ");
System.out.printf("%,.2f", totArea2);
System.out.print(" and a cost of $");
System.out.printf("%,.2f", totCost2);
System.out.print(".");
break;
case "no" :
break;
}
}
}
>Solution :
When you do sc.nextDouble(), you type an input followed by a newline character (the enter button).
So the double s gets the value you entered but in your scanner buffer, you still have a newline character.
You can do this
-
After your sc.nextDouble(), do a sc.next() / sc.nextLine() to clear out the buffer.
-
Another option is to
String s = sc.nextDouble();
Then attempt to convert the s to an integer.