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.
我想让它这样,我有一个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...
}
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
4 个解决方案
#1
4
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:
对于一个完整的程序,你可以订购最多5个披萨,保存并打印到最后,请看下面:
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]]);
}
}
#2
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).
“如果”消失了。(我鼓励您看看java.util。映射到可能比标签数组更干净的数据结构)。
#3
0
Don't use capitalized words (Pizzas
) for local primitives in Java. Conventionally, those are class names.
在Java中,不要对本地原语使用大写的单词(Pizzas)。按照惯例,这些是类名。
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/elses中去掉。如果您需要做的只是获取披萨类型的名称,那么这里有一些示例,说明您根本不需要一组case,您只需要为后续的任何用途分配。
If there are some unique things per case, you can use a 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",
};
#4
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:
在这里,您可以做一些事情来优化代码。首先,删除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:
其次,可以用switch语句替换if语句,如下所示:
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:
但是,我们实际上可以进一步优化它,这将完全减少对switch语句的需要。首先,我们需要一个变量来存储挑选的披萨。我们可以用另一个数组,5个元素长。创建如下所示:
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:
如您所见,我们甚至不需要使用ifs或交换机,因为我们可以使用赋值。我们可以使用数组的括号语法来继续优化。可以像这样初始化数组:
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!
#1
4
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:
对于一个完整的程序,你可以订购最多5个披萨,保存并打印到最后,请看下面:
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]]);
}
}
#2
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).
“如果”消失了。(我鼓励您看看java.util。映射到可能比标签数组更干净的数据结构)。
#3
0
Don't use capitalized words (Pizzas
) for local primitives in Java. Conventionally, those are class names.
在Java中,不要对本地原语使用大写的单词(Pizzas)。按照惯例,这些是类名。
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/elses中去掉。如果您需要做的只是获取披萨类型的名称,那么这里有一些示例,说明您根本不需要一组case,您只需要为后续的任何用途分配。
If there are some unique things per case, you can use a 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",
};
#4
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:
在这里,您可以做一些事情来优化代码。首先,删除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:
其次,可以用switch语句替换if语句,如下所示:
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:
但是,我们实际上可以进一步优化它,这将完全减少对switch语句的需要。首先,我们需要一个变量来存储挑选的披萨。我们可以用另一个数组,5个元素长。创建如下所示:
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:
如您所见,我们甚至不需要使用ifs或交换机,因为我们可以使用赋值。我们可以使用数组的括号语法来继续优化。可以像这样初始化数组:
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!