I'm working on a textbook exercise for my upcoming Computer Science class, and I've run into a problem, specifically, the goal of the program is to have three items inputted (as String), and three prices inputted, then have them outputted. In addition, if one of the names of the items is "Peas" (not case sensitive), also display the average price, if not, display "no average output".
The problem that I'm having is that the program never displays the "no average output" as needed, even if none of the values are "peas", "Peas", etc.
In addition to the code below, I've tried the following..
- Just declare the boolean peas, don't initialize as false
- Integrate the average price/no average price string as part of the result string and display one big message box instead of two
Use a separate if statement within a for loop outside of the original for loop that receives data inputted
// Import JOptionPane to display message boxes of the data inputed import javax.swing.JOptionPane; public class PeaPrice { public static void main(String[] args) { // Declare arrays for the 3 String names, the 3 double prices, and the average price String[]names=new String[3]; double[]prices=new double[3]; double avg; // Initialize the boolean value for if "peas" is inputed, and the result to be displayed boolean peas=false; String result="Results... \n"; // Loop 3 times to receive 3 string values for(int i=0; i<3; i++){ names[i] = JOptionPane.showInputDialog("Please input the name of item number " + (i+1) + ":"); // If the string entered is peas, set the boolean to true if(names[i].toLowerCase()=="peas"){ peas=true; } } // Loop 3 times to receive 3 double values for(int i=0; i<3; i++){ prices[i] = Double.parseDouble((JOptionPane.showInputDialog("Please input the price of item number " + (i+1) + ":"))); } // Loop 3 times to go through each array index for price and name to add them to the result string to be displayed for(int i=0; i<3; i++){ result +="Item name: " + names[i] + " Item price: $" + prices[i] + "\n"; } // Display the result string JOptionPane.showMessageDialog(null, result); //Calculate the average price avg = (prices[0]+prices[1]+prices[2])/3; // Display the average price accordingly based on the boolean value if(peas=true){ JOptionPane.showMessageDialog(null, "Average price: $" + avg); } else if (peas=false){ JOptionPane.showMessageDialog(null, "no average output"); } System.exit(0);
} }
Thank you for the assistance!
EDIT Sadly the solution provided by the other issue I was referred to, I tried modifying the if statement to the following and still have the same problem
if(names[i].toLowerCase().equals("peas")){
peas=true;
}
I also tried removing the toLowerCase and still have the same problem
if(names[i].equals("peas")){
peas=true;
}
EDIT 2 Solved - thank you @jegesh!