gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:26:15 25 4
gpt4 key购买 nike

我对编程还比较陌生。我现在正在尝试制作一个程序,并且正在尝试弄清楚如何做某事。我希望你们能帮助我,因为我只是不知道该怎么做...

所以,首先,我制作了一个数组并用东西填充它:

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";

我想做一个 IF 语句(在一段时间内)。我会把代码放在这里,然后再解释。

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...

}

现在在'Insert something here' 位,我想尝试将数组(比萨饼)中的文本存储到某个变量中,稍后我可以打印出来.. . 因此,例如,如果用户输入“1”,则它需要:“1-Cheese”并将其存储在一个变量中,我可以稍后打印出来...

此外,我想让它变得干净,这样就不会有 10 个 IF 语句提示每个变量...?

我不知道这是否可行,但非常感谢任何帮助! :D

我希望我在这里问的是可以理解的...

如果可能的话,您能否解释一下您在每个步骤中所做的事情,以便我能够真正理解正在发生的事情,并可能在以后使用相同的代码,而不是仅仅复制和粘贴代码?我有点菜鸟所以我认为我学到的越多以后我可以使用的越多......非常感谢! :D

最佳答案

您可以将整个系列的 if 语句替换为:

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

// Here, saveName has the pizza name.

有关允许您订购最多五个比萨饼、保存批处理并在最后打印出来的完整程序,请参见下文:

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]]);
}
}

关于Java - IF 'input' = 'this' {将数组中的字符串存储到变量中},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10477306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com