2

I'm relatively new to programming. I'm trying to make a program at the moment, and I'm trying to figure out how I can do something. I hope you guys can help me as I just don't know how to do this...

So, first of all, I have made an array and filled it with stuff:

String[] pizza = new String[10];
    pizza[0] = "1- Cheese";
    pizza[1] = "2- Wedge";
    pizza[2] = "3- Bacon";
    pizza[3] = "4- Hawaiian";
    pizza[4] = "5- Vegetarian";
    pizza[5] = "6- Pepperoni";
    pizza[6] = "7- Ham";
    pizza[7] = "8- Apple";
    pizza[8] = "9- Grape";
    pizza[9] = "10- Italian";

I want to make it so that I have an IF statement (which is inside a while). I'll just put the code here, and explain after.

int pizzaCounter = 0;

        while(pizzaCounter < 5)
        {

            Scanner pizzaPick = new Scanner(System.in);
            int Pizzas = pizzaPick.nextInt();

            if (Pizzas == 1)
            {
                *Store "1- Cheese" (From pizza[0]) into a variable*

                pizzaCounter++;
            }
            if (Pizzas == 2)
            {
                *Store "2- Wedge" (From pizza[0]) into a variable*

                pizzaCounter++;
            }
            if (Pizzas == 3) etc...

        }

Now at the 'Insert something here' bit, I want to try to make it so that it stores the text from the array(pizza) into some variable which I can print out later... So for example if the user inputs '1' then it takes: "1-Cheese" and stores it in a variable which I can print out later...

Also, I want to make it clean, so that there aren't 10 IF statements prompting each variable thing...?

I don't know if this is even possible, but any help is greatly appreciated! :D

I hope what I am asking here is understandable...

Please, if possible, could you explain what you are doing at each of the steps, so that I can actually understand what is happening, and maybe use the same code later, instead of just copying it and pasting the code? I'm kind of a noob so I think that the more I learn the more I can use later on... Thanks so much! :D

2
  • 1
    this is a very nice first question, btw. Commented May 7, 2012 at 5:57
  • (off-topic) to follow Java naming conventions, variables should be lowercaseStartingCamelCase. Instead of your variable being called Pizzas, call it pizzas instead. Commented May 7, 2012 at 6:02

4 Answers 4

4

You can replace the entire series of if statements with something like:

string saveName = "";
if ((Pizzas >= 0) && (Pizzas <= 9)) {
    saveName = pizza[Pizzas];           // This is "insert something here".
    pizzaCounter++;
}

// Here, saveName has the pizza name.

For a full blown program which allows you to order up to five pizzas, saving the lot and printing them out at the end, see below:

import java.util.Scanner;

public class testprog {
    public static void main (String args[]) {
        String[] pizzaList = {" 0 - End of order",
            " 1 - Cheese", " 2 - Wedge", " 3 - Bacon", " 4 - Hawaiian",
            " 5 - Vegetarian", " 6 - Pepperoni", " 7 - Ham", " 8 - Apple",
            " 9 - Grape", "10 - Italian"};

        int[] orderList = new int[5];  // Ordered pizzas
        int pizzaCount = 0;            //    and count.

        Scanner pizzaPick = new Scanner(System.in);
        while (pizzaCount < 5) {
            // Output the menu.

            System.out.println ("Choose a pizza:");
            for (int i = 0; i < pizzaList.length; i++)
                System.out.println ("   " + pizzaList[i]);

            // Get input, check, and add pizza.

            int thisPizza = pizzaPick.nextInt();
            if (thisPizza == 0) break;

            if ((thisPizza > 0) && (thisPizza < pizzaList.length))
                orderList[pizzaCount++] = thisPizza;

            if ((thisPizza < 0) || (thisPizza >= pizzaList.length))
                System.out.println ("Invalid input of " + thisPizza);
        }

        // Output all pizzas.

        for (int i = 0; i < pizzaCount; i++)
            System.out.println ("Ordered: " + pizzaList[orderList[i]]);
    }
}
1
  • Wow!!! Thank you so much!!! I really appreciate this!!! :D :D :D I don't even know how to thank you!!! One last thing, I don't really understand 'for' statements that much, otherwise I'd try and figure it out myself... But how can I make it so that after each time I choose a pizza, I put in something like: System.out.println("1-Large, 2-small) Scanner pizzaSize = new Scanner(System.in); int Size = pizzaSize.nextInt(); if(Size == 1) { price = price + smallPrice; } else if(Size == 2) { price = price + largePrice Commented May 7, 2012 at 6:52
0
String[] PIZZA_LABELS = new String[]{ "1- Cheese", "2- Wedge" ... }
String label;
while(pizzaCounter < 5)
{
        Scanner pizzaPick = new Scanner(System.in);
        int Pizzas = pizzaPick.nextInt();
        label  = PIZZA_LABELS[Pizzas - 1]; // 1-indexed vs 0-indexed
        ...
        System.out.println(label);

'if' is gone. (I would encourage you to look at java.util.Map for a possibly cleaner data structure than the label array).

2
  • ALL_CAPS should be reserved for static final constants. Commented May 7, 2012 at 6:10
  • 1
    Well, that should be a static final constant anyway :-) Commented May 7, 2012 at 20:06
0

Don't use capitalized words (Pizzas) for local primitives in Java. Conventionally, those are class names.

You want to distinguish between what is the same regardless of the value of Pizzas -- eg, you increment pizzaCounter each time -- and leave that out of the if/elses. If all you need to do is get the name of the type of pizza, then you have a few examples here of how you don't need a set of cases at all, you just need to assign for whatever subsequent use.

If there are some unique things per case, you can use a switch:

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

BTW, you can initialize arrays like this:

String eg[] = {
   "one",
   "two",
   "three",
};
0

There are a few things you can do here to optimize the code. First, drop the while loop in favor of a for loop, like so:

for (int i = 0; i < 5; i++) {
    // Will loop 5 times
}

Second, you could replace the if statements with a switch statement, like so:

switch (pizzaPick.nextInt()) {
    case 0:
        // Do something
        break;
    case 1:
        // Do something else
        break;
    case 2:
        // Etc.
        break
}

However, we can actually optimize this even further, which will drop the need for switch statements at all. First, though, we need a variable to store the picked pizzas. We can use another array, which will be 5 elements long. Create it like so:

String[] pickedPizzas = new String[5];

Now we can do stuff with that to store the picked pizzas. We can then do this in each loop to save the picked pizzas:

pickedPizzas[i] = pizza[pizzaPick.nextInt()];

As you can see, we didn't even need to use ifs or a switch, since we can just use assignment. We can continue the optimization by using bracket syntax for arrays. You can initialize arrays like this:

String[] strArray = {"one", "two", "three", ...};

This saves space and is simpler. To top it off, move the declaration of your scanner outside the loop. Placing it inside the loop will cause it to be re-created and destroyed each time the loop executes, due to the loop's scope. Placing it outside the loop will remedy this.

Here's what the final code might look like:

// Hold all the pizza names
String[] pizzas = {
    "1- Cheese",
    "2- Wedge",
    "3- Bacon",
    "4- Hawaiian",
    "5- Vegetarian",
    "6- Pepperoni",
    "7- Ham",
    "8- Apple",
    "9- Grape",
    "10- Italian"
    };

// Create a variable to hold the selected pizzas
String[] pickedPizzas = new String[5];

// Create Scanner outside loop
Scanner scanner = new Scanner(System.in);

// Loop to get picked pizzas
for (int i = 0; i < 5; i++) {
    // Save picked pizza, subtracting 1 since arrays start at 0
    pickedPizzas[i] = pizzas[scanner.nextInt() - 1];
}

// Do stuff with the users picked pizzas!
5
  • String[] pizzas = new String[] { is redundant, you can just use String[] pizzas = {. Commented May 7, 2012 at 6:13
  • @goldilocks Fair enough. Changed. Commented May 7, 2012 at 6:17
  • Thanks! :) I tried it but, I noticed that I need to add something else in, after an integer is picked.. Like, input is 1, then it prompts: "Standard or Large Size?", which I've got sorted.. Sorry, probably should've stated that in the question... :/ Commented May 7, 2012 at 6:23
  • @Vanya If the extra operation varies per number, you can use the switch statement I outlined. If not, you can simply insert it in the for loop. If you give me some extra specifics, I might be able to show you an example. Commented May 7, 2012 at 6:26
  • Ok, here was my code which I had success with, and could've kept going up to 10, except it would've looked extremely messy. stackoverflow.com/questions/10477824/… Commented May 7, 2012 at 6:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.