简体   繁体   English

Java-IF'input'='this'{将字符串从数组存储到变量中}

[英]Java - IF 'input' = 'this' {store string from array into variable}

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). 我要制作一个IF语句(在一段时间内)。 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... 现在在“在此处插入一些内容”位,我想尝试使其存储在数组(比萨饼)中的文本到某个变量中,以便稍后我可以打印出来...例如,如果用户输入“ 1 '然后它取:“ 1-Cheese”并将其存储在一个变量中,我以后可以打印出来...

Also, I want to make it clean, so that there aren't 10 IF statements prompting each variable thing...? 另外,我想使它整洁,以便没有10条IF语句提示每个变量。

I don't know if this is even possible, but any help is greatly appreciated! 我不知道这是否有可能,但是任何帮助将不胜感激! :D :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 :d

You can replace the entire series of if statements with something like: 您可以将整个一系列if语句替换为以下内容:

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]]);
    }
}
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). (我鼓励您查看java.util.Map,以获得比标签数组更干净的数据结构)。

Don't use capitalized words ( Pizzas ) for local primitives in Java. 不要在Java中将大写单词( Pizzas )用于本地基元。 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. 您想区分相同的东西,而不管Pizzas的价值如何-例如,您每次都增加pizzaCounter并将其排除在if / els中。 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 : 如果每种情况都有一些独特的东西,可以使用一个switch

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

BTW, you can initialize arrays like this: 顺便说一句,您可以像这样初始化数组:

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

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: 首先,将while循环放到for循环中,如下所示:

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

Second, you could replace the if statements with a switch statement, like so: 其次,您可以将if语句替换为switch语句,如下所示:

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. 但是,我们实际上可以进一步优化它,这将完全不需要switch语句。 First, though, we need a variable to store the picked pizzas. 不过,首先,我们需要一个变量来存储挑选的披萨。 We can use another array, which will be 5 elements long. 我们可以使用另一个数组,该数组的长度为5个元素。 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. 如您所见,我们甚至不需要使用ifs或switch,因为我们可以只使用赋值。 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!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM