Array Method with If statement in Java - java

I am a graduate student learning the Java program. As a homework assignment, we are to do the following:
Create a menu of items where the user can input choices into an array
Create a method that figures out the prices of the items chose and return the sum
Right now, my output shows that the total being returned from the method is actually adding all the prices in the if statement instead of coordinating them with the user input array that was copied (see example output on bottom). We have not touched upon anything further than the standard array (no ArrayList or other methods). Please offer any advice, I will do my best to figure it out.
import java.util.Arrays;
import java.util.Scanner;
public class Online_Purchasing_HW6 {
public static final int ARRAY_LENGTH = 10; //Length of the array
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //Reads user input
int[] naMenuChoice = new int [ARRAY_LENGTH]; //Array for items chosen
String[] naMenu = new String [ARRAY_LENGTH]; //Array for menu items
int[] naItemPrice = new int [9]; //Array for item prices
String sCustomerName; //String for customer's name
int nChoice = 0; //Option chosen in menu by user/Used as Index
int nSum = 0; //Sum of items chosen
double dTotalPrice = 0; //Total price plus taxes
double dTaxes = 0; //Total taxes to be applied to total
//Declare Constants
final int SENTINEL = 10; //Used to end loop
final double SALES_TAX = 0.065; //Sales tax to be used
//Choices for menu denoted by strings
String sChoice1 = "1. Smartphone" + "\t" + "\t" + "$249";
String sChoice2 = "2. Smartphone Case" + "\t" + "$39";
String sChoice3 = "3. PC Laptop" + "\t" + "\t" + "$1149";
String sChoice4 = "4. Tablet" + "\t" + "\t" + "$349";
String sChoice5 = "5. Tablet Case" + "\t" + "\t" + "$49";
String sChoice6 = "6. eReader" + "\t" + "\t" + "$119";
String sChoice7 = "7. PC Desktop" + "\t" + "\t" + "$899";
String sChoice8 = "8. LCD Monitor" + "\t" + "\t" + "$299";
String sChoice9 = "9. Laser Printer" + "\t" + "$399";
String sChoice10 = "10. Complete my order";
//Prompt user for name
System.out.print("Please enter your name: ");
//Read customer's name
sCustomerName = input.nextLine();
//Menu of items for purchase
System.out.print("\n");
System.out.println("Best Purchase Products");
System.out.println(sChoice1);
System.out.println(sChoice2);
System.out.println(sChoice3);
System.out.println(sChoice4);
System.out.println(sChoice5);
System.out.println(sChoice6);
System.out.println(sChoice7);
System.out.println(sChoice8);
System.out.println(sChoice9);
System.out.println(sChoice10);
//Prompt user for item selection
System.out.print("Please select an item from the menu above: ");
naMenuChoice[nChoice] = input.nextInt();
//Loop to read integers from user
while (naMenuChoice[nChoice] != SENTINEL) {
//adds 1 everytime more than one item is chosen by the user
nChoice++;
//Prompt user for another choice since he/she has not chosen option "10"
System.out.print("Please select another item from the menu above: ");
naMenuChoice[nChoice] = input.nextInt();
} //end of while loop
System.out.print(Arrays.toString(naMenuChoice));
//If option 10 if chosen, the loop will end with this message
System.out.println("\n" + "Thank you for ordering with Best Purchase, " + sCustomerName );
//call calculateTotalPrice method passing Array
nSum = nCalculatePrice(naMenuChoice);
//Formulas
//Sales Tax
dTaxes = SALES_TAX * nSum;
//Total Amount Due
dTotalPrice = dTaxes + nSum;
System.out.println("Total items ordered: " + nChoice);
System.out.println("Price of items ordered: $" + nSum);
System.out.println("Sales tax: $" + dTaxes);
System.out.println("Total amount due: $" + dTotalPrice);
}//end of main method
//Method for calculating price
public static int nCalculatePrice(int[] naChoicesToPrice){
int nTotalPrice = 0; //int value to return
int nIndex = 0; //used as counter
int nItemPrice = 0; //used to assign price of items
int[] naAddedPrices = new int[ARRAY_LENGTH]; //new array for assigning prices
//For loop to sum up all entries from naItemPrice array
for (nIndex = 0; nIndex < ARRAY_LENGTH; nIndex++){
naAddedPrices[nIndex] = naChoicesToPrice[nIndex];
//end of For Loop
if (nIndex == 1) {
nItemPrice = 249;
nTotalPrice += nItemPrice;}
if (nIndex == 2) {
nItemPrice = 39;
nTotalPrice += nItemPrice;}
if (nIndex == 3) {
nItemPrice = 1149;
nTotalPrice += nItemPrice;}
if (nIndex == 4) {
nItemPrice = 349;
nTotalPrice += nItemPrice;}
if (nIndex == 5) {
nItemPrice = 49;
nTotalPrice += nItemPrice;}
if (nIndex == 6) {
nItemPrice = 119;
nTotalPrice += nItemPrice;}
if (nIndex == 7) {
nItemPrice = 899;
nTotalPrice += nItemPrice;}
if (nIndex == 8) {
nItemPrice = 299;
nTotalPrice += nItemPrice;}
if (nIndex == 9) {
nItemPrice = 399;
nTotalPrice += nItemPrice;}
} //end of for loop
return nTotalPrice;
}//end of naCalculatePrice method
}//end of class
Corresponding output for the program is:
Please enter your name: John Smith
Best Purchase Products
1. Smartphone $249
2. Smartphone Case $39
3. PC Laptop $1149
4. Tablet $349
5. Tablet Case $49
6. eReader $119
7. PC Desktop $899
8. LCD Monitor $299
9. Laser Printer $399
10. Complete my order
Please select an item from the menu above: 9
Please select another item from the menu above: 10
[9, 10, 0, 0, 0, 0, 0, 0, 0, 0]
Thank you for ordering with Best Purchase, John Smith
Total items ordered: 1
Price of items ordered: $3551
Sales tax: $230.815
Total amount due: $3781.815
As you can see, I chose only one item from the menu but it adds up all the prices. I've been on this assignment for 2 weeks so far and I'm growing desperate. I've read most articles on this site pertaining to this subject, read many articles on just methods and arrays, respectively and still can't formulate a working program.Any help would be appreciated.

Nice work so far.
In your for loop to sum up, you have to look into naMenuChoices to see what the customer has ordered. Remember, you may find a 0 or a 10 there, in which case you should not add anything to the sum. Good luck, you’re not that far from your goal.
You may want to make yourself a class for the product/items like
public class Product {
private String itemText;
private int itemPrice;
public Product(String itemText, int itemPrice) {
this.itemText = itemText;
this.itemPrice = itemPrice;
}
public int getItemPrice() {
return itemPrice;
}
#Override
public String toString() {
return itemText + "\t\t$" + itemPrice;
}
}
Fill 9 objects of this class into an array, use them for building the sChoice Strings and use it instead of the naItemPrice array. Modify my code to your needs. It should give a better overview of the code. And eliminate the risk of accidentally charging another price from the customer than the one announced.

for (int i = 0; i < ARRAY_LENGTH; i++){
if(naChoicesToPrice[i]==0 || naChoicesToPrice[i]==10){
nItemPrice = 0;
}
else{
if (naChoicesToPrice[i] == 1) {
nItemPrice = 249;
}
if (naChoicesToPrice[i] == 2) {
nItemPrice = 39;
}
if (naChoicesToPrice[i] == 3) {
nItemPrice = 1149;
}
if (naChoicesToPrice[i] == 4) {
nItemPrice = 349;
}
if (naChoicesToPrice[i] == 5) {
nItemPrice = 49;
}
if (naChoicesToPrice[i] == 6) {
nItemPrice = 119;
}
if (naChoicesToPrice[i] == 7) {
nItemPrice = 899;
}
if (naChoicesToPrice[i] == 8) {
nItemPrice = 299;
}
if (naChoicesToPrice[i] == 9) {
nItemPrice = 399;
}
}
nTotalPrice += nItemPrice;
} //end of for loop
return nTotalPrice;
}

Related

error msgs after second loop attempt

I'm working on another assignment and am stuck. First off, I realize I probably won't get the results I want from this code, but at the moment I can't run the code to even see how close or far away I am. I'm sure I'm missing something simple and hope that something will pop out to someone here so I can move past this point. My mother tongue is English but I'm living in Sweden and trying to learn code in a Swedish class so I added //for translations.
Again, I am working with very basic code so am not looking for an easy hack, more of just some insight to where I have gone wrong.
My assignment is to ask the user to enter 10 numbers, store those as an array. Then, offer the user 4 options to calculate those numbers and a 5th option to quit the program.
Here's what I have so far:
package inlämningsuppgift3;
import java.util.Scanner;
import java.util.Arrays;
public class Inlämningsuppgift3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int nr;
int antal = 0;
int[] num = new int[10];
int sum = 0;
int min = 0;
int max = 0;
for (nr = 0; nr < 10; nr++) {
System.out.println("Ange ett tal " + (nr+1) + " : ");
int tal = input.nextInt();
num[nr] = tal;
if (nr == 0) { //first number
min = tal;
max = tal;
}
else { // All other numbers
if (tal > max) { max = tal; }
if (tal < min) { min = tal; }
}
sum = sum + tal;
}
{
// What would you like to do?
System.out.println("Välj vad du vill göra?");
// Show largest number
System.out.println("1: Visa storsta talet.");
// Show smallest number
System.out.println("2: Visa minsta talet.");
// Show average
System.out.println("3: Visa medeltalet.");
// Show all numbers
System.out.println("4: Visa alla inmatade tal.");
// Quit
System.out.println("5: Avsluta");
}
do {
int k = input.nextInt();
if (k == 1) {
// Largest number is:
System.out.println("Storsta talet är: " + max);
}
else if (k == 2) {
// Smallest number is:
System.out.println("Minsta talet är: " + min);
}
else if (k == 3) {
// Average number is:
System.out.println("Medeltalet är: " + sum/10);
}
else if (k == 4) {
// All the entered numbers:
System.out.println("Alla tal: " + num[10] + ", ");
}
else if (k==5) {
// Goodbye
System.out.println("Hej då!");
break;
}
else {
System.out.println("Felaktigt, prova igen.");
// Unrecognized, try again.
}
while (k<5);
}
}
}
I'm getting error on the last 3 } and I'm not sure why. Are they in the wrong place? I've tried moving them around, I've tried deleting them (obviously, didn't help either) I tried changes to my {} placement above in the code and just haven't found a way around this error. Thank you in advance for any input!
java do-while syntax is:
do {
// Statements
}while(Boolean_expression);
so, change it to:
int k = 0;
do {
k = input.nextInt();
if (k == 1) {
System.out.println("Storsta talet är: " + max);
} else if (k == 2) {
System.out.println("Minsta talet är: " + min);
} else if (k == 3) {
System.out.println("Medeltalet är: " + sum / 10);
} else if (k == 4) {
System.out.println("Alla tal: " + num[10] + ", ");
} else if (k == 5) {
System.out.println("Hej då!");//good bye
break;
} else {
System.out.println("Felaktigt, prova igen.");
}
} while (k < 5) ;
and after while line must be two } now.
Hej Hej!
I made the modifications I think like you asked to make it 'just about work'
package Dunno;
import java.util.Scanner;
public class NumberCollector { //No special characters in source files,
//Can get transformed during deployment
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int nr;
int antal =0;
int[] num = new int[10];
int sum = 0;
int min=0;
int max=0;
for (nr=0; nr<10; nr++)
{
System.out.println("Ange ett tal " + (nr+1) + " : ");
int tal = input.nextInt();
num[nr]=tal;
if(nr == 0) //first number
{
min=tal;
max=tal;
}
else //all other numbers
{
if(tal>max)max =tal;
if(tal<min) min=tal;
}
sum = sum + tal;
}
System.out.println("Välj vad du vill göra?");
//what would you like to do?
System.out.println("1: Visa storsta talet.");
//Show largest number
System.out.println("2: Visa minsta talet.");
//show smallest number
System.out.println("3: Visa medeltalet.");//show average
System.out.println("4: Visa alla inmatade tal.");
//show all numbers
System.out.println("5: Avsluta");//quit
while (true) //Moved the stop condition to start of the loop makes it easier to read logically.
{
int k = input.nextInt();
if (k==1)
{
System.out.println("Storsta talet är: " + max);
//largest number is:
}
else if (k==2)
{
System.out.println("Minsta talet är: " + min);
//smallest number is:
}
else if (k==3)
{
System.out.println("Medeltalet är: " + sum/10);
//average number is:
}
else if (k==4)
{
System.out.println("Alla tal: " + num[10] + ", ");
//all the entered numbers:
}
else if (k==5)
{
System.out.println("Hej då!");//good bye
break;
}
else
{
System.out.println("Felaktigt, prova igen.");
//unrecognized, try again.
}
};
}
}
I only had to move around some braces.
It seems to broadly do what you want? It throws an exception if you ask for result 4, I'll leave that to you :)
Maybe this will be a good starting point? Consider replacing the loop with a switch/case condition would be nicer to read and maintain?

Java Change Prompt Order

I am currently working on a java program that has to do with taking classes and the amount of credits for each class. I have everything set up how I need it, except the order.
I would like it to ask for a class, then how many credits that class is, then ask for the next class, and those credits, and so on. Right now, it will ask for all of the classes, then all of the credits. Here's the code I have:
//Jake Petersen
import java.util.Scanner;
public class test1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.println("Please enter a course:");
courseArray[i] = scan.nextLine();
}
int creditArray[] = new int[courses];
for (int i = 0; i < creditArray.length;) {
System.out.println("Please enter how many credits "+ courseArray[i] + " is:");
int input = scan.nextInt();
if (input >= 1 && input <= 4) {
creditArray[i++] = input;
}
}
int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}
Do all the prompts in a single for loop:
import java.util.Scanner;
public class test1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
int creditArray[] = new int[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.print("Please enter a course:");
courseArray[i] = scan.nextLine();
System.out.print("Please enter how many credits "+ courseArray[i] + " is:");
String credits = scan.nextLine();
int input = Integer.parseInt(credits);
if (input >= 1 && input <= 4) {
creditArray[i] = input;
}
else {
creditArray[i] = 0;
}
} int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}
Of course this assumes that the 2 arrays have the same size. Perhaps you want to prompt for a class count first, to know how large to make the arrays, or grow them dynamically.

Math Logic in Java for Lemonade Stand Game

I am writing the lemonade stand game in Java but I am having a bit of trouble trying to figure out the perfect recipe. I mean something like if weather is Sunny and temperature is greater than 85 the perfect recipe would be 8 lemons, 6 cups of sugar and 12 ice cubes per cup. I have most of the code done, except the math logic seems a little off. Please let me know how can I improve the code. I included all the code so you can get a better idea on how all the logic goes so far.
public static void main(String[] args) {
///declaration of variables
int playAgain;
int days, customers = 120;
int CUPS_PITCHER = 14;
double money = 20.00, earned = 0;
double [] cupsPrice = {0.93, 1.65, 2.77}, lemonsPrice = {0.98, 2.05, 4.38}, sugarPrice = {0.74, 1.63, 3.31}, icePrice = {0.99, 2.01, 3.95};
//inventory
///string input
String cupsS = "", lemonsS = "", sugarS = "", iceS = "";
//int input values
int cups = 0, lemons = 0, sugar = 0, ice = 0;
//String for Pitcher
double priceCup;
int lemonsPitcher, sugarPitcher, iceCup;
////array for items options
String [] cupsOptions = {"25","50","100"};
String [] lemonsOptions = {"10","30","75"};
String [] sugarOptions = {"8","20","48"};
String [] iceOptions = {"100","250","500"};
int temperature;
String [] weather = {"Sunny","Hazy","Cloudy","Overcast","Rainny"};
JOptionPane.showMessageDialog(null,"Welcome to our Lemonade Stand Game");
days = getDays();
///set flag for loops
boolean ingredients, cupsFlag, lemonsFlag, sugarFlag, iceFlag;
boolean [] flag = {false,false,false,false};
NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
String [] itemName = {"Cups","Lemons","Sugar","Ice Cubes"};
String [][] itemOptions = {cupsOptions,lemonsOptions,sugarOptions,iceOptions};
for(int i=1; i<=days; i++){
/////random weather
Random rand = new Random();
int randomWeather = rand.nextInt(5);
//random temperature from 59 to 99
temperature = rand.nextInt(99-59) + 59;
int response = 0;
///loop while not play game
while(response != 1){
String[] options = new String[] {"Buy", "Play Game", "Cancel"};
response = JOptionPane.showOptionDialog(null, "You currently have " + defaultFormat.format(money) + " Day " + i + "\nCups: " + cups + " *** Lemons: " + lemons + "\nSugar: " +
sugar + " *** Ice: "+ice + "\nHigh Temperature: " + temperature + "\nWeather Forecast: " + weather[randomWeather], "Inventory",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
ingredients = false;
///if buy ingredientes ** when they click buy
while(response == 0 && !ingredients){
String[] optionsBuy = new String[] {"Buy Cups", "Buy Lemons", "Buy Sugar", "Buy Ice","Back to Game"};
String line1 = "\n25 Cups: $" + cupsPrice[0] + " 10 Lemons: $" + lemonsPrice[0]
+ " 8 Cups of Sugar: $" + sugarPrice[0] + " 100 Ice Cubes: $"+icePrice[0];
String line2 = "\n50 Cups: $" + cupsPrice[1] + " 30 Lemons: $" + lemonsPrice[0]
+ " 20 Cups of Sugar: $" + sugarPrice[1] + " 250 Ice Cubes: $"+icePrice[1];
String line3 = "\n100 Cups: $" + cupsPrice[2] + " 75 Lemons: $" + lemonsPrice[2]
+ " 48 Cups of Sugar: $" + sugarPrice[2] + " 500 Ice Cubes: $"+icePrice[2];
int responsePurchase = JOptionPane.showOptionDialog(null, "You currently have " + defaultFormat.format(money) + " Day " + i + line1 + line2 + line3 + "\nHigh Temperature: " + temperature + "\nWeather Forecast: " + weather[randomWeather], "Inventory",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
null, optionsBuy, optionsBuy[0]);
double [][] priceOptions = {cupsPrice,lemonsPrice,sugarPrice,icePrice};
int [] qty = {0,0,0,0};
for(int j=0; j<4; j++){
if(responsePurchase == j)
qty[j] = buyItems(itemName[j],itemOptions[j],flag[j],money);
//money = money - itemPrice[j][0];
}
///deduct money
for(int k=0;k<4;k++){
for(int j=0;j<3;j++){
if(qty[k] == Integer.parseInt(itemOptions[k][j])){
money = money - priceOptions[k][j];
}
}
}
////add items purchased
cups += qty[0];
lemons += qty[1];
sugar += qty[2];
ice += qty[3];
//System.out.println(itemOptions[0][1]);
/*
if(qty[0] == 25){
money = money - cupsPrice[0];
}
if(qty[0] == 50){
money = money - cupsPrice[1];
}
if(qty[0] == 100){
money = money - cupsPrice[2];
}
// buy lemons
cupsFlag = false;
if (responsePurchase == 0) {
int qty = buyItems("Cups",cupsOptions,cupsFlag,money);
if (qty != 0) {
cups += qty;
}
}
// buy lemons
lemonsFlag = false;
if (responsePurchase == 1) {
int qty = buyItems("Lemons",lemonsOptions,lemonsFlag,money);
if (qty != 0) {
lemons += qty;
}
}
*/
///go back to game when back to game click
if(responsePurchase == 4){
ingredients = true;
}
}///end while buy ingredients
}///end while buy
JTextField fieldCup = new JTextField("0.25");
JTextField fieldLemons = new JTextField("4");
JTextField fieldSugar = new JTextField("4");
JTextField fieldIce = new JTextField("4");
Object[] fields = {"Price per Cup in Cents", fieldCup,"Lemons per Pitcher", fieldLemons,"Sugar per Pitcher", fieldSugar, "Ice per Cup", fieldIce};
int responsePitcher = JOptionPane.showConfirmDialog(null,fields,"Price",JOptionPane.OK_CANCEL_OPTION);
if(responsePitcher == JOptionPane.CANCEL_OPTION){
int stopGame = JOptionPane.showConfirmDialog(null,"Do you wish to cancel the game? All progress will be lost","",JOptionPane.YES_NO_OPTION);
if(stopGame == JOptionPane.YES_OPTION){
System.exit(0);
}
}
while(!validateDouble(fieldCup.getText()) || !validateInt(fieldLemons.getText()) || !validateInt(fieldSugar.getText()) || !validateInt(fieldIce.getText())){
if(responsePitcher == JOptionPane.CANCEL_OPTION){
int stopGame = JOptionPane.showConfirmDialog(null,"Do you wish to cancel the game? All progress will be lost","",JOptionPane.YES_NO_OPTION);
if(stopGame == JOptionPane.YES_OPTION){
System.exit(0);
}
}
JOptionPane.showMessageDialog(null,"One of the inputs is incorrect! try Again","ERROR",JOptionPane.ERROR_MESSAGE);
responsePitcher = JOptionPane.showConfirmDialog(null,fields,"Price",JOptionPane.OK_CANCEL_OPTION);
}
priceCup = Double.parseDouble(fieldCup.getText());
lemonsPitcher = Integer.parseInt(fieldLemons.getText());
sugarPitcher = Integer.parseInt(fieldSugar.getText());
iceCup = Integer.parseInt(fieldIce.getText());
for(int k=0; k<5; k++){
if(weather[randomWeather].equals(weather[k])){
////if weather is not sunny reduce possible customers
if(!weather[randomWeather].equals(weather[0])){
customers = customers - (customers * k/15);
}
}
}
//System.out.println(customers);///testing results
//System.out.println(fieldCup.getText());///testing results
System.out.println(customers);///testing results
//showBar();
///perfect recepie
if(temperature > 58){
///if sunny
if(weather[randomWeather].equals(weather[0])){
}
}
//too expensive or not right ingredients reduce possible customers
if(priceCup > 0.25){
customers = customers - (customers * 10/100);///reduce customers by 10%
}
if(lemonsPitcher > 7 || lemonsPitcher < 5){
customers = customers - (customers * 10/100);///reduce customers by 10%
}
if(sugarPitcher > 7 || sugarPitcher < 5){
customers = customers - (customers * 10/100);///reduce customers by 10%
}
if(iceCup > 10 || iceCup < 6){
customers = customers - (customers * 15/100);///reduce customers by 15%
}
///determine max cups according to inventory
int maxCupsLemons = (lemons / lemonsPitcher) * CUPS_PITCHER;
int maxCupsSugar = (sugar / sugarPitcher) * CUPS_PITCHER;
int maxCupsIce = (ice / iceCup);
int maxCupsp = cups;
int [] maxCups = {maxCupsLemons, maxCupsSugar, maxCupsIce, maxCupsp};
System.out.println(Arrays.toString(maxCups));
int minValue = maxCups[0];
for(int m=0;m<maxCups.length;m++){
if(maxCups[m] < minValue){
minValue = maxCups[m];
}
}
System.out.println(minValue);
if(minValue < customers){
customers = minValue;
}
System.out.println(customers);///testing results
////profit
earned = priceCup * customers;
money += earned;
///deduct inventory
//14 cups per pitcher
int lemonsSpent = (customers / CUPS_PITCHER) * lemonsPitcher;
int sugarSpent = (customers / CUPS_PITCHER) * sugarPitcher;
lemons = lemons - lemonsSpent;
sugar = sugar - sugarSpent;
cups = cups - customers;
JOptionPane.showMessageDialog(null,"Your profit for day " + i + " is " + defaultFormat.format(earned));
/////reset variables for next day
customers = 120;
earned = 0;
ice = 0;
}
//JOptionPane.showMessageDialog(null,days);
}
}
I think your problem is on the pricing.
Better leave it as 14 cups. Then generate the price per cup.
First, you should have a standard measure on how many cups of an ingredient will be in one pitcher. That way, you will have a basis.
Let's say. 8 lemons + 6 cups of sugar + 12 ice cubes = 1 pitcher
Multiply the cup price. 8 * 0.98, etc. then add it to other ingredients price.
But, it will be better and easier if you will remove the pitcher from the price computation. Since you will sell it by cups.
I'll give you a tip in formulating a program's logic. Most of the time, the obvious way to do it is the easiest way. Put yourself in the position of the program, if you were the program, what will you do?
In improving your program's logic, check every thing your program does. Ask yourself, is it the most likely thing I will do?
If your program works, never fear to take risks. Try other ways, try other algorithms, and read. Then decide which of those will improve your work. Most of the time trying something new begets failure, but that's the bittersweet way of learning.
Happy coding!

Stuck on Java program (java.io.*;)?

The purpose of my program is to ask what the temperature(F) is and what the weather condition outside is like.
The weather condition can be either sunny(1), raining(2), cloudy(3) or snowing(4.) The numbers 1-4 will be used to clarify what the weather condition is (I'm not sure how to do it any other way...)
Then, depending on the combination of temp and weatherCondition I want to be able to display 3 garments out of 10 choices, based on the combo of temp and weatherCondition.
I'm still learning so I apologize if my question or problem seems mundane...
At the moment when a user enters the temp and weatherCondition, a response is given depending on the combo of the two inputs (ex. hot-sunny, freezing-snowing).
Instead, I would like to create one or more txt files and have each one named something like hotSunny.txt for example. Inside these txt files I've listed 10 types of garments. I ultimately want the program to recognize which combo matches its appropriate txt file and then randomly display 3 of the 10.
What I've got so far...
public static void main(String[] args)
{
double temperature;
int weatherCondition;
String input;
input = JOptionPane.showInputDialog("What is " +
"the current temperature?");
temperature = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Sweet I now know the temperature! " +
"Now please take a look out the nearest window is it Sunny , Rainy ," +
" Cloudy or Snowy? " +
"(1 = Sunny) (2 = Raining) " +
"(3 = Cloudy) (4 = Snowing)");
weatherCondition = Integer.parseInt(input);
if (temperature <= 32){
if (weatherCondition == 4){
freezingSnowing();
} else if (weatherCondition == 3){
freezingCloudy();
} else if (weatherCondition == 2){
freezingRain();
} else {
freezingSunny();
}
}..........
else if ((temperature >= 33) && (temperature <= 50)) {
else if ((temperature >= 51) && (temperature <= 75)) {
else if ((temperature >= 76) && (temperature <= 140)) {
public static void freezingSnowing()
{
JOptionPane.showMessageDialog(null, "It's is snowing! I recommend that you dress very warm" +
"and wear a large coat that is preferably water proof.");
}
Your freezingSnowing method should look like this:
public static void freezingSnowing() {
file = new File(MyWeatherApp.class.getResource
(path + "freezingSnowing.txt"));
// path to the txt file
// where path is the local path to the file
scanner = new Scanner(file);
ArrayList<String> garments = new ArrayList<>(10);
while(scanner.hasNextLine()) {
garments.add(scanner.nextLine());
}
ArrayList<Integer> indices = new ArrayList<>(3);
for(int i = 0; i < 3; i++) {
while(true) { // watch out for duplicates
int rand = (int)(Math.random() * 9);
if(!indices.contains(rand))
break;
}
indices.add(rand);
JOptionPane.showMessageDialog(null, "It's is snowing! " +
"I recommend that you dress very warm " +
"and wear " + garments.get(indices.get(1)) +
", " garments.get(indices.get(2)) +
" and " + garments.get(indices.get(3)) +
".");
}
This is my version of randomly picking item.
public static void main(String[] args) {
String[] weatherCond = new String[] {"cold", "hot"};
ArrayList<String> garmets = new ArrayList<String>();
garmets.add("clothes");
garmets.add("hat");
garmets.add("gloves");
garmets.add("coat");
ArrayList<String> pick;
int ITEM = 3;
int temperature = 29;
if (temperature >= 30) { // hot condition
System.out.println("weather condition " + weatherCond[0]);
pick = garmets;
for (int i = 0; i < ITEM; i++) {
int idx = (int) (Math.round(Math.random() * pick.size()) % pick.size());
System.out.print(pick.get(idx) + " " );
pick.remove(idx);
}
} else {
System.out.println("weather condition " + weatherCond[1]);
pick = garmets;
for (int i = 0; i < ITEM; i++) {
int idx = (int) (Math.round(Math.random() * pick.size()) % pick.size());
System.out.print(pick.get(idx) + " " );
pick.remove(idx);
}
}
}
Also, if you want to use a fix set of garmets for a specific weather condition, you could use a hashmap which uses weather condition as a key and garmet groups as a value.

I'm having a issue with my while loop displaying two prints the second time around

This is what I have:
import java.util.*;
import java.text.*;
public class Proj4 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String again = "y";
final int MAX_STUDENTS = 100;
final int MIN_EXAM = 0;
final int MAX_EXAM = 50;
final int MIN_FINAL = 0;
final int MAX_FINAL = 100;
String[] names = new String[MAX_STUDENTS];
int[] exams = new int[MAX_STUDENTS * 4];
int student = 1;
DecimalFormat df = new DecimalFormat("#0.0");
do {
System.out.print("Please enter the name of student " + student
+ ": ");
String line;
line = s.nextLine().toUpperCase();
names = line.split(" ");
for (int i = 0; i < 4; i++) {
if (i == 3) {
System.out.print("Please enter score for Final Exam: ");
exams[i] = s.nextInt();
}
else {
System.out.print("Please enter score for Exam " + (i + 1)
+ ": ");
exams[i] = s.nextInt();
if (student == 1) {
if ((exams[0] < MIN_EXAM || exams[0] > MAX_EXAM)
|| (exams[1] < MIN_EXAM || exams[1] > MAX_EXAM)
|| (exams[2] < MIN_EXAM || exams[2] > MAX_EXAM)) {
System.out.println("Invalid enter 0-50 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
} else if (exams[3] < MIN_FINAL || exams[3] > MAX_FINAL) {
System.out.println("Invalid enter 0-100 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
} else if (student == 2) {
if ((exams[0] < MIN_EXAM || exams[0] > MAX_EXAM)
|| (exams[1] < MIN_EXAM || exams[1] > MAX_EXAM)
|| (exams[2] < MIN_EXAM || exams[2] > MAX_EXAM)) {
System.out.println("Invalid enter 0-50 only...");
System.out.print("Please re-enter score: ");
exams[i + 4] = s.nextInt();
} else if (exams[3] < MIN_FINAL || exams[3] > MAX_FINAL) {
System.out.println("Invalid enter 0-100 only...");
System.out.print("Please re-enter score: ");
exams[i + 4] = s.nextInt();
}
}
}
}
System.out.print("do you wish to enter another? (y or n) ");
again = s.next();
if (again.equalsIgnoreCase("y"))
student++;
} while (again.equalsIgnoreCase("y"));
System.out.println("***Class Results***");
System.out
.println(names[1]
+ ","
+ names[0]
+ " "
+ "Exam Percentage: "
+ ((float) (exams[0] + exams[1] + exams[2] + exams[3]) / (MAX_EXAM * 3 + MAX_FINAL))
* 100 + "%");
if (student == 2)
;
System.out
.println(names[3]
+ ","
+ names[2]
+ " "
+ "Exam Percentage: "
+ ((float) (exams[4] + exams[5] + exams[6] + exams[7]) / (MAX_EXAM * 3 + MAX_FINAL))
* 100 + "%");
if (student == 3)
;
System.out
.println(names[5]
+ ","
+ names[4]
+ " "
+ "Exam Percentage: "
+ ((float) (exams[8] + exams[9] + exams[10] + exams[11]) / (MAX_EXAM * 3 + MAX_FINAL))
* 100 + "%");
if (student == 4)
;
System.out
.println(names[7]
+ ","
+ names[6]
+ " "
+ "Exam Percentage: "
+ ((float) (exams[12] + exams[13] + exams[14] + exams[15]) / (MAX_EXAM * 3 + MAX_FINAL))
* 100 + "%");
}
}
My program seems to be running exactly the way i want/need it to, the only problem is, when i allow the program to run again it outputs two strings on the same line like this:
Please enter the name of student 2: Please enter score for Exam 1:
I don't know what to do to fix this. is there something in my code that messes up only on the second and probably 3rd and 4th times?
Remove semicolons after ifs
if (student == 3)
; // <- remove it
System.out.println(//...
because now Java understands it as
if (student == 3){}
System.out.println(//...
change
System.out.print("do you wish to enter another? (y or n) ");
again = s.next();
to
System.out.print("do you wish to enter another? (y or n) ");
again = s.nextLine();
next will not consume new line mark, so when you use nextLine after next it will consume only this new line mark and go to another instruction. Same rule apply for nextInt.
To store array of student names you could use two dimensional array of Strings
String[][] names = new String[MAX_STUDENTS][];
and store student names in each row based on student number
names[student] = line.split(" ");
To get first name of first student you will have to use this form
names[0][0]; //you probably know that indexes in array starts from zero
To get names of all students you can iterate over each rows and then over columns
for(int stId=0; stId<student; stId++){
for(int nameNumber=0; nameNumber<names[stId].length; nameNumber++){
// print names[stId][nameNumber]`
If you want the strings to print on a new line use println instead of print, or include a linebreak character in your string.

Categories

Resources