Parallel Array for a Java project - java

I have searched to see if there was a question like this already but I did not find one. So for this school project, I am supposed to make a program with arrays to look up and print the names and prices for coffee orders. I have most of the program done but I only get one dialog box to pop up and if I add an XXX it quits the system completely without giving an output.
I know if I add some more addIn = JOptionPane.showInputDialog("Enter coffee add-in or XXX to quit: "); it would give me another pop-up window but I am still having trouble with it has I want it to give me one line at a time like if I say "Cream" it says "Cream price is $0.89" and if I enter "Vanilla" it says "Sorry we do not carry that" and when I enter "XXX" it would just says "Order total is $2.89".
import javax.swing.*;
public class JumpinJive
{
public static void main(String args[]) throws Exception
{
// Declare variables.
String addIn; // Add-in ordered by customer.
final int NUM_ITEMS = 5; // Named constant
// Initialized array of add-ins.
String addIns[] = {"Cream", "Cinnamon", "Chocolate", "Amaretto", "Whiskey"};
// Initialized array of add-in prices.
double addInPrices[] = {.89, .25, .59, 1.50, 1.75};
boolean foundIt = false;
int x; // Loop control variable.
double orderTotal = 2.00; // All orders start with a 2.00 charge
// Get user input.
addIn = JOptionPane.showInputDialog("Enter coffee add-in or XXX to quit: ");
// Write the rest of the program here.
for(int it=0; it < NUM_ITEMS; it++){
if(addIns[it].equals(addIn)){
//Output the product name and the price
System.out.println("Name of the product :" + addIns[it] + "\nPrice of the product:" + addInPrices[it]);
//Output the total for the price of the product
System.out.println("Total Price of the product :"+ (orderTotal + addInPrices[it]));
//If foundIt is true
foundIt = true;
break;
}
}
//See if it is found
if(foundIt)
{
//Prints a Error Message
System.out.println("Sorry, but we do not carry that product.");
}
} // End of main() method.
} // End of JumpinJive class.
Am I missing something or am I misinterpreting possibly what the assignment is going for? Thank you in advance!!

but I only get one dialog box to pop up and if I add an XXX it quits the system completely without giving an output
You need some kind of loop, maybe something like...
do {
// Get user input.
addIn = JOptionPane.showInputDialog("Enter coffee add-in or XXX to quit: ");
if (!addIn.equals("XXX")) {
// Write the rest of the program here.
}
} while (!addIn.equals("XXX"));
I'd recommend having a look at Control Flow Statements and have a look a the The while and do-whole statements for more details
Also, you're not keeping a running total of the order...
So, instead of...
System.out.println("Name of the product :" + addIns[it] + "\nPrice of the product:"
+ addInPrices[it]);
//Output the total for the price of the product
System.out.println("Total Price of the product :" + (orderTotal + addInPrices[it]));
Maybe something like...
String item = addIns[it];
double price = addInPrices[it];
orderTotal += price;
JOptionPane.showMessageDialog(null, item + " is $" + price + " - Order total: $" + orderTotal);
will keep track of the current order total
And this...
if (foundIt) {
//Prints a Error Message
System.out.println("Sorry, but we do not carry that product.");
}
Is going to display an error message when the item is found (i.e. if (true) {...}, you want to negate the question, maybe something like...
if (!foundIt) {
JOptionPane.showMessageDialog(null, "Sorry, but we do not carry that product.");
}

Related

Need to exit a loop once the correct input is entered

Please see my code below for a quiz game. I have been trying to figure out for 2 days now how to correctly code the loop at the option menu. Once I know how to code it correctly I would be able to code in the rest of the loops I need for the other questions.
The way I have it coded right now it gets stuck on "Invalid selection, please try again." infinitely.
Someone please help me with the correct code. :(
Everything I've been able to find related to this utilizes Scanner input instead of the JOptionPane.
package team1;
//this is required for JOptionPane to work
import javax.swing.JOptionPane;
//this allows for exception throwing
import java.io.*;
public class GameV2 {
public static void main(String[] args) throws IOException {
/**
* Version 2 Updates:
* - added 2 more sets of questions and answers
* - created a decision structure to determine the path of the game based on +
the user's menu choice
* - created a decision structure to indicate whether to the user whether an +
answer is correct or incorrect.
* - added point values to each question and a totalScore accumulator which +
displays at the end of the game.
*/
// display an introduction to the game.
JOptionPane.showMessageDialog(null, "Welcome to Team 1's Game Version 2!");
// prompt the user for his/her first name
String firstname;
firstname = JOptionPane.showInputDialog("What is your first name?");
// prompt the user for his/her last name
String lastname;
lastname = JOptionPane.showInputDialog("What is your last name?");
// display a customized hello message to the user
JOptionPane.showMessageDialog(null, "Hi, " + firstname + " " + lastname + "!");
**// create a menu and display it to the user
// then ask the user to choose an option
String menu = "1) See Rules and Play the Game\n"
+ "2) Play the Game\n"
+ "3) Exit\n"
+ "Please enter your choice: (1 or 2 or 3) ";
String userChoice = JOptionPane.showInputDialog(menu);
JOptionPane.showMessageDialog(null, "You chose option " + userChoice);
// display the rules
String rules = "Rules:\n"
+ "The game will display total 3 multiple choice questions," +
" with 4 possible answers per question.\n"
+ "Once you answer the question, the correct answer will be displayed" +
" and the game will advance to the next question.\n"
+ "If you answer the question correctly, you will gain a point.\n"
+ "Each point is added to a total score that will be displayed at the" +
"end of the game.\n";
// declare an integer that reads the user input
int numericChoice = Integer.parseInt(userChoice);
boolean valid = (numericChoice == 1 || numericChoice == 2 || numericChoice == 3);
if (numericChoice == 1){
// display the rules then start the game
JOptionPane.showMessageDialog(null, rules);
}
else if (numericChoice == 2){
// start the game
JOptionPane.showMessageDialog(null, "Let's play the game.\n");
}
else if (numericChoice == 3){
// exit the game
System.exit(0);
}
while (!valid){
JOptionPane.showMessageDialog(null, "Ivalid selection, please try again");
JOptionPane.showInputDialog(menu);
continue;
}
To make your implementation work like you intend to you should rewrite your loop, e.g. like the following:
boolean valid = false;
do {
final String userChoice = JOptionPane.showInputDialog(menu);
final int numericChoice = Integer.parseInt(userChoice);
JOptionPane.showMessageDialog(null, "You chose option " + userChoice);
if (numericChoice == 1) {
valid = true;
// display the rules then start the game
JOptionPane.showMessageDialog(null, rules);
} else if (numericChoice == 2) {
valid = true;
// start the game
JOptionPane.showMessageDialog(null, "Let's play the game.\n");
} else if (numericChoice == 3) {
valid = true;
// exit the game
System.exit(0);
} else {
JOptionPane.showMessageDialog(null, "Ivalid selection, please try again");
}
} while (!valid);
You should also remove the lines
String userChoice = JOptionPane.showInputDialog(menu);
JOptionPane.showMessageDialog(null, "You chose option " + userChoice);
before the loop because they will be executed inside of it.
If you do it like that than your loop has the following cycle:
Get and store user input (userChoice and numericChoice*)
Show user their input
Handle input
if 1 or 2 or 3 set valid to true and continue according to choice
or
Show an error and repeat from step 1
* You should think about handling the case when userChoice can not be parsed into a number

User input from scanner method to array of 5 indexes also gives user ability to delete any index

User input from scanner method to array of 5 indexes also gives user ability to delete any index matching with string from one of the index.
ALL I want to achieve in this is in this while loop I would like to settle city (option 1), which means creating one as you can probably see from my code. This is where user will type any name they like no restrictions. once they settle the city loops starts again. However it does remember that user created a city earlier. I can have upto 5 cities. There is cost associate with settling new city. I know how to do those conditionals. I am just not sure about this string array.
ArrayList or Array class is not allowed.
where as, option 2 I can demolish any of the city i have created by giving user lists of city they have made earlier. I have to keep minimum of at least one city.
IF you are wondering then this is based on Civilization game.
Please ask for clarification as this may not be
straight forward. thanks
while (playing) {
System.out.println("\nPlease make your selection!");
System.out.println("\n1. Settle a City"
+ "\n2. Demolish a City"
+ "\n3. Build Militia"
+ "\n4. Research Technology"
+ "\n5. Attack Enemy City"
+ "\n6. End Turn\n");
String gameChoice = userinput.nextLine();
if (gameChoice.equals("1")) {
System.out.println("\nWhat would you like to"
+ " name your city?");
String cityname = userinput.nextLine();
cityname = cityNames[0];
} else if (gameChoice.equals("2")) {
System.out.println("What city would you like to demolish?");
for (int i = 0; i < 5 ; i++) {
System.out.print(cityNames[i]);
System.out.print("");
}
} else if (gameChoice.equals("3")) {
System.out.println("You have military points");
} else if (gameChoice.equals("4")) {
System.out.println("You have Research Technology points");
} else if (gameChoice.equals("5")) {
System.out.println("You have zero points");
} else {
System.out.println(" Thanks for playing ");
}
playing = false;
}
First, here:
String cityname = userinput.nextLine();
cityname = cityNames[0];
You are assigning cityname to user input and then you are assigning it to something in cityNames array, that doesn't make sense, maybe you pasted wrong or something, but just in case, this should be the other way around, like this:
cityNames[0] = cityname;
You have playing = false at the end so the loop is gonna just end when user types the city name, you need to either remove this playing = false or use continue; after cityNames[0] = cityName;, that's gonna go to the next iteration of a loop, without going all the way down to playing = false.

Do While Loop, update name of maximum donor

I'm trying to write a program that needs to stop when the target of £500 has been met. I have to use a DO WHILE loop to do this.
It needs to record how many donations it receives before it reaches £500, also it needs to record the name of the person with the highest donation given and what the largest donation was.
I cannot get the program to update the name of the person with the highest donation. The code I have so far is below. Please tell me where I am going wrong.
I have a red line coming up under 'namemax' when I try to call it at the end outside of the loop, saying 'not initialized'
enter codeimport java.util.Scanner;
/**
* Created by IntelliJ IDEA.
* Date: 11/02/2015
* Time: 15:45
* UPDATE COMMENT ABOUT PROGRAM HERE
*/
public class DoWhile
{
public static void main(String[] args)
{
Scanner keyboard= new Scanner(System.in);
final double TOTAL=500;
String name,namemax;
double donation, donationTotal=0,currentMax=0;
int howManyDonation=0;
do
{
System.out.println("Please enter your name below");
name = keyboard.next();
System.out.println("");
System.out.println("Please enter the amount you would like to donate below");
donation = keyboard.nextDouble();
howManyDonation++;
donationTotal = donationTotal+donation;
if(donation>currentMax)
{
currentMax=donation;
namemax=name;
}//if
}//doWhile
while(donationTotal!=TOTAL);
System.out.println("The total number of donations is " + howManyDonation);
System.out.println("The largest donation was " + currentMax);
System.out.println("The name of the person with the largest donation is " + namemax);
}//main
}//class
here
Just change this line
String name,namemax;
into this:
String name,namemax = null;
Furthermore, change this
while(donationTotal != TOTAL);
into this:
while(donationTotal < TOTAL);
You have a pretty simple problem here. You are updating namemax inside of an if loop only. That means that as far as the code is concerned, there is a possible situation in which it could never be assigned. In practice, because of what you are doing, that can't actually happen but the compiler doesn't understand that.
To fix it,
change
string name,namemax;
to
string name;
string namemax = "";
That should take care of it.
it gives at least one sutuation where namemax not will be set. So you have to initialize the string.
Simply change
String name,namemax ;
To
String name,namemax = null;
or
String name,namemax = "";
The compiler can't guarantee that you'll actually set the namemax before you exit the loop. You should initialize namemax to the empty string to fix this problem.

Console Calculator error java

So everything is working fine for this calculator besides for the askCalcChoice1. Since askCalcChoice1 is a string, I am calling it wrong (obviously). The error says it cannot convert string to int, as well as convert int to boolean. However, when i make the inputOperation as a string, it breaks the other 2 calls below askCalcChoice1. (it breaks displayRedults and askTwoValues because those are not strings). I do not know how to format askCalcChoice in order to call for this method that is written in another class wihtout breaking anything. askCalcChoice is written as a string which i pasted below the oopCalculator code. Is there any way and can someone please show me how to write that portion of that code in oopCalculator?
int inputOperation; // user to choose the function
askCalcChoice1 myAskCalcChoice1 = new askCalcChoice1();
//menu becomes a complete string below
String menu = "Welcome to Hilda Wu's Calculator\t\t"
+ "\n1. Addition\n"
+ "2. Subtraction\n"
+ "3. Multiplication\n"
+ "4. Division\n"
+ "5. Exit\n\n";
calculatorCommands.pickNewSymbol(menu); //complete menu will be picked up as a string and display
calculatorCommands.putDownSymbol();
while (inputOperation = myAskCalcChoice1.calcChoice()) { //this will call for myAskCalcChoice1 class
calculatorCommands.pickNewSymbol("\n"); //pick up the class
calculatorCommands.putDownSymbol(); //display the class
askTwoValues myAskTwoValues = new askTwoValues();
float[] myFloats = myAskTwoValues.inputFloats(inputOperation);
displayResults myDisplayResults = new displayResults();
float result = myDisplayResults.showResults(inputOperation, myFloats);
String strFormat = "The answer is: " + result + "\n\n"; //print out The answer is as a string
calculatorCommands.pickNewSymbol(strFormat); //pick up string from above
calculatorCommands.putDownSymbol(); //display string
calculatorCommands.pickNewSymbol(menu); // pick up menu from the beginning of code, loop to calculator menu
calculatorCommands.putDownSymbol(); //display menu as loop
}
calculatorCommands.pickNewSymbol("\nThank you for using Hilda Wu's Calculator\n"); //when user choose to exit calculator
calculatorCommands.putDownSymbol();
}
String calcChoice() {
String input;
do { //do loop will continue to run until user enters correct response
System.out.print("Please enter a number between 1 and 5, A for Addition, S for Subtraction, M for Multiplication, or D for Division, or X for Exit: ");
try {
input = readInput.nextLine(); //user will enter a response
if (input.equals("A") || input.equals("S") || input.equals("M") || input.equals("D") || input.equals("X")) {
System.out.println("Thank you");
break; //user entered a character of A, S, M, or D
} else if (Integer.parseInt(input) >= 1 && Integer.parseInt(input) <= 5) {
System.out.println("Thank you");
break; //user entered a number between 1 and 5
} else {
System.out.println("Sorry, you have entered an invalid choice, please try again.");
}
continue;
}
catch (final NumberFormatException e) {
System.out.println("You have entered an invalid choice. Try again.");
continue; // loop will continue until correct answer is found
}
} while (true);
return input;
}
}
To start with, you are calling showResults with two arguments:
int choice
and
float [] f
Choice is never used.
You use input variable instead in your switch but on default you return the error showing choice.
Better pass choice as an argument in the function and be sure it is char and not other type.
Also this is not the form of a good stated question. I will not rate it down but please remake it so the whole code is correctly shown. I can not make sense of it easily. I might misunderstood it already. Please do not add comments between, be sure you have correct indentation and you got all the code in.
If you need to comment do it afterwards. It's not very complicated, just show us the code and ask what is wrong later ;)
If choice was meant to pass in the switch... then do it, but not as int but as char.

java.lang.NumberFormatException - Can't find where the error is

I am getting this message:
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:454)
at java.lang.Integer.parseInt(Integer.java:527)
at fdc.programming.VendingMachine.InsertMoney(VendingMachine.java:70)
at fdc.programming.VendingMachineDriver.main(VendingMachineDriver.java:30)
Java Result: 1
I had been trying to work out, how to do a validate loop so that only positive integers can be accepted and I gave up for now, but I did not change anything and put everything back as it was before messing around. Now when I try to enter a number it gives the above error but there are no errors in Netbeans that I can use to figure out what is wrong! Please be aware that I have only done one basic module in Java for college ;)
My code is:
public class VendingMachine
{
String sinsertMoney, sinsertMoney2; // Money inserted value for parsing into int
String productName; // Name of product
int insertMoney, insertMoney2; // Money inserted by customer (int = pence)
int price; // Price of products on sale
int changeLeft; // Change left from inserted money after selection
int again; // variable for deciding program repeat
DecimalFormat pence = new DecimalFormat("#p"); // Format display output for pence
public void InsertMoney() {
String soption; // Variable for machine operation
productName = " Nothing";
insertMoney = 0; // Default inserted money initialised to zero
insertMoney2 = 0; // Default additional inserted money initialised to zero
price = 0; // Initialising money variables
// Vending machine welcome dialog
soption = JOptionPane.showInputDialog(
"============================================"
+ "\nWelcome to the College Vending Machine!"
+ "\n============================================"
+ "\n\nOptions: i for insert money, s for select item, q for quit."
+ "\n\n============================================");
if ("q".equals(soption)) { // If user chooses q: quit
JOptionPane.showMessageDialog(null, "Have a Nice Day!");
System.exit(0); // terminate application
}
if ("i".equals(soption)) { // if user chooses i: insert money
JOptionPane.showInputDialog(
"============================="
+ "\nPlease enter some money (in pence)"
+ "\n============================="); // Inserting money
insertMoney = Integer.parseInt(sinsertMoney); // Parsing for calculations
}
if ("s".equals(soption)) { // if user chooses s: select item
}
}
I can't see where you've declared sinsertMoney but it looks like you've forgotten to assign the result of your call to JOptionPane.showInputDialog to something, hence why that value is still null when you try to parse it.
Try this:
sinsertMoney = JOptionPane.showInputDialog(
"============================="
+ "\nPlease enter some money (in pence)"
+ "\n============================="); // Inserting money
insertMoney = Integer.parseInt(sinsertMoney);
You need to get the entered value in sinsertMoney like:
sinsertMoney = JOptionPane.showInputDialog(
"============================="
+ "\nPlease enter some money (in pence)"
+ "\n=============================");
And also implement null check on the sinsertMoney for cancel operation and empty strings.

Categories

Resources