I am pretty new to Java and still practicing. I did a simple exercise with user-defined methods. The code is in below. When I run the code,it seems like the if statement(in whileloop) is not working. The code ignores the if-statement and directly loop back. for example output like this(no place to input var response): Enter item name: milk Enter price for milk: 1 Enter the quantity for this item: 2 More items? (y/n) Enter item name:
import java.util.*;
public class TotalPrice {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
double total = getTotal();
print(total);
}
public static double getTotal()
{
double total = 0;
Boolean moreItems = true;
String response;
while(moreItems)
{
total += getItemPrice(getItemName());
System.out.println("More items? (y/n)");
response = in.nextLine();
if(response.equalsIgnoreCase("n"))
{ moreItems = false;}
}
return total;
}
public static String getItemName()
{
String name;
System.out.println("Enter item name: ");
name = in.nextLine();
return name;
}
public static double getItemPrice(String value)
{
double price = 0;
try{
System.out.println("Enter price for " + value + ":");
price = in.nextDouble();
}
catch(Exception e)
{
System.out.println("Invalid data type entered.");
e.printStackTrace();
}
int quantity = getItemQuantity();
return quantity * price;
}
public static int getItemQuantity()
{
System.out.println("Enter the quantity for this item: ");
int quantity = in.nextInt();
return quantity;
}
public static void print(double total)
{
System.out.printf("The total for your grocery items is: $%5.2f, "
+ "thanks for shopping with us!\n\n", total);
}
}