英文:
Array being continuously filled inside of a switch-case unintentionally
问题
我最近在处理一个有些问题的项目。简单来说,我希望我的程序按照以下方式运行:
-
用户输入一个数字,然后检查该数字是否是有效选项。如果不是有效选项,则出现错误消息,并再次显示主菜单。
-
如果选择了有效选项,一个 switch case 语句接收所选选项,并运行每个 case 语句内部的代码。
-
一旦在 switch case 部分运行的代码完成运行,它将循环回到顶部,重新显示主菜单,然后继续运行步骤 1-3,直到用户选择选项 4 退出程序。
我遇到的问题是,当我进入 case 1 时,它似乎会循环遍历一个不应该循环遍历的代码片段,并且继续向数组中添加 Triangle 对象,这是这里的代码:
if ((side1 == 0 || side2 == 0 || side3 == 0)) {
// 问题从这里开始
triangleArray[trianglesAdded] = new Triangle();
System.out.println("Default triangle created");
trianglesAdded += 1;
}
其中 triangleArray 是一个 Triangle 对象数组,其大小为 100,trianglesAdded 用于跟踪实际添加到数组中的三角形数量,也是该数组的索引变量。由于它不断地向该数组添加 Triangle 对象,我会收到错误,因为一旦数组达到限制,就不能再容纳更多的 Triangle 对象,这也意味着我不能循环回到主菜单。
所以我的问题是:如何使它能够停止循环遍历这部分代码(因为它只应该发生一次,每次只添加一个 Triangle 对象到数组中),并且使它能够在运行后回到完整的循环,再次显示主菜单?
以下是完整的代码:
do {
while (validMenuOption == false) {
// 显示菜单选项...
}
switch (menuOption) {
case 1:
// ...
if ((side1 == 0 || side2 == 0 || side3 == 0)) {
// 问题从这里开始
triangleArray[trianglesAdded] = new Triangle();
System.out.println("Default triangle created");
trianglesAdded += 1;
} else {
// ...
}
break;
case 2:
// ...
break;
case 3:
// ...
break;
case 4:
// ...
break;
default:
// ...
break;
}
} while (true);
英文:
I am currently having trouble with something I was working on recently. To keep it short and simple, I wanted my program to function as follows:
-
User inputs a number, and that number is checked to see if it's a valid option. If it's not a valid option, an error message appears and makes the main menu appear again.
-
If a valid option is chosen, a switch case takes in the chosen option and runs the code that's inside of each case statement.
-
Once the code is done running in the switch-case portion, it would loop back up to the top and re-display the main menu, and process 1-3 would continue to run until the user selects option 4 to quit the program.
The problem that I've seem to run into is that when I go into case 1, it likes to loop through a certain piece of code that's not meant to be looped through and continues to add a Triangle object to the array, which is this piece here:
if((side1 == 0 || side2 == 0 || side3 == 0))
{
// Problem with do-while loop begins here
triangleArray[trianglesAdded] = new Triangle();
System.out.println("Default triangle created");
trianglesAdded += 1;
}
where triangleArray is an array of Triangle objects which has a size of 100, trianglesAdded keeps track of how many triangles are actually added to the array, as well as be a variable for the index of that array. Since it keeps adding Triangle objects to this array, I get an error since the array can't hold any more Triangle objects once it's hit its limit, meaning that I also cannot loop back up to the main menu.
So my question is: how can I make it to where it can stop looping through this portion (since it's only supposed to occur once and only add one Triangle object to the array at a time) and also make it to where it can come full circle and display the main menu once again after running through?
Full code is below:
do
{
while(validMenuOption == false)
{
System.out.println("1. Enter data for a new triangle.");
System.out.println("2. Print all triangles sorted by area, smallest to largest.");
System.out.println("3. Print only triangles with a specific color.");
System.out.println("4. Exit the program.");
System.out.print("\nPlease enter in a number to select an option: ");
menuOption = sc.nextInt();
if(menuOption >= 1 && menuOption <= 4)
{
validMenuOption = true;
}
else
{
System.out.println("Invalid menu choice. Please try again.\n");
validMenuOption = false;
}
if(menuOption == 1 && trianglesAdded == triangleArray.length - 1)
{
System.out.println("The triangle array has hit the max. You are unable to add more triangles.");
validMenuOption = false;
}
}
switch(menuOption)
{
case 1:
...
// If one, two, or all of the side lengths given are zero and the color of the triangle is 1, creates a default triangle
// with the sides being 1 and the color being 1
if((side1 == 0 || side2 == 0 || side3 == 0))
{
// Problem begins here
triangleArray[trianglesAdded] = new Triangle();
System.out.println("Default triangle created");
trianglesAdded += 1;
}
// If side lengths greater than zero were given, creates a triangle with the side lengths and color given
else
{
triangleArray[trianglesAdded] = new Triangle(side1, side2, side3, color);
System.out.println("Triangle created with specified size and color");
}
break;
case 2:
...
break;
case 3:
...
break;
case 4:
...
break;
default:
...
break;
}
} while(true);
答案1
得分: 1
好的,以下是翻译好的部分:
你的程序出现了一个错误。所以你要做的就是当你遇到错误时所有人都会做的事情:逐行在脑中计算你的程序应该做什么。然后将其与计算机告诉你它认为你的代码是什么意思进行比较。在你的大脑和计算机产生分歧的地方,你找到了一个错误。
- 你的程序表示 'validMenuOption' 为假。
- 我输入 '1'。
- validMenuOption 被设置为真,然后我们循环执行 '输入 while 块'。
- vMO 现在为真,所以 while 循环结束,我们继续执行。
- switch 运行,然后我们执行 '添加一个三角形' 部分。
- 外部循环继续执行。
- validMenuOption 仍然为真。
- 所以...整个 '获取一些输入' 的 while 循环零次运行。
你可能希望首先重置 validMenuOption,或者你希望将其设为 do {} while (); 循环。
英文:
Well, you have a bug. So you do what everybody does when you hit a bug: You calculate what your program is supposed to do, line-by-line, in your head. Then you compare it to what the computer tells you it thinks your code means. Where your brain and your computer disagree, you found a bug.
- Your program says that 'validMenuOption' is false.
- I enter '1'.
- validMenuOption is set to true, and we loop the 'input while block'.
- vMO is now true, so the while loop is ended, we continue.
- The switch runs, and we do the 'add a triangle' part.
- the outer loop loops.
- validMenuOption is still true.
- so.. that whole 'get some input' while loop runs zero times.
Presumably you either want to reset validMenuOption first, or you want that to be a do {} while ();
loop.
答案2
得分: 0
我会完全删除validMenuOption
变量,并将其移到一个单独的函数中,类似于这样:
public int getMenuOption() {
Scanner sc = new Scanner(System.in);
int menuOption = 0;
System.out.println("1. 输入新三角形的数据。");
System.out.println("2. 按面积排序打印所有三角形,从小到大。");
System.out.println("3. 打印具有特定颜色的三角形。");
System.out.println("4. 退出程序。");
System.out.print("\n请输入数字以选择选项:");
menuOption = sc.nextInt();
if(menuOption < 1 || menuOption > 4) {
return 0;
} else {
return menuOption;
}
}
在你的main
方法或任何运行switch
语句的地方,做类似以下的操作:
boolean run = true;
int[] triangleArray = new int[100];
int trianglesAdded = 0;
while (run) {
int menuOption = getMenuOption();
switch(menuOption) {
case 0:
System.out.println("无效的菜单选择。请重试。\n");
break;
case 1:
if(trianglesAdded == triangleArray.length - 1) {
System.out.println("三角形数组已达到最大值。无法再添加更多三角形。");
run = false;
} else {
triangleArray[trianglesAdded] = 1; // 或者你想要的任何数字或对象
System.out.println("默认三角形已创建");
trianglesAdded += 1;
}
break;
default:
break;
}
}
为了简单起见,我将triangleArray
设为一个int
数组。
我还添加了一个名为run
的boolean
变量,它在设置为true
时运行,进入while
循环时从getMenuOption()
函数获取menuOption
的值。
现在,如果它得到了0
,它会打印出菜单选项是假的,然后中断并回到循环的开头,再次调用getMenuOption()
。如果输入了1
,它就会进入case 1
。
你提到的问题:
当数组达到限制时,我会出现错误,因为数组无法再容纳更多的三角形对象
通过在添加之前检查长度,就像我所做的那样,已经解决了。
要退出,你可以添加另一个case
,将run
设置为false
:
case 4:
run = false;
等等。
这是一个供你立即测试的repl链接。我已经将数组的大小更改为2
,所以你可以看到在达到限制时它会停止。
英文:
I would remove validMenuOption
variable completely and move it to separate function, something like this:
public int getMenuOption() {
Scanner sc = new Scanner(System.in);
int menuOption = 0;
System.out.println("1. Enter data for a new triangle.");
System.out.println("2. Print all triangles sorted by area, smallest to largest.");
System.out.println("3. Print only triangles with a specific color.");
System.out.println("4. Exit the program.");
System.out.print("\nPlease enter in a number to select an option: ");
menuOption = sc.nextInt();
if(menuOption < 1 || menuOption > 4) {
return 0;
} else {
return menuOption;
}
}
See how I return 0
when option is out of range and otherwise I return menuOption
.
Now in your main
or wherever you run switch
statement do something like this:
boolean run = true;
int[] triangleArray = new int[100];
int trianglesAdded = 0;
while (run) {
menuOption = getMenuOption();
switch(menuOption) {
case 0:
System.out.println("Invalid menu choice. Please try again.\n");
break;
case 1:
if(trianglesAdded == triangleArray.length - 1) {
System.out.println("The triangle array has hit the max. You are unable to add more triangles.");
run = false;
} else {
triangleArray[trianglesAdded] = 1; // or whatevery number or object you want
System.out.println("Default triangle created");
trianglesAdded += 1;
}
break;
default:
break;
}
}
For the sake of simplicity I have made triangleArray
to be an int
array.
I also added a boolean
variable run
which runs while it is set to true
and upon entering while
it gets menuOption
value from getMenuOption()
function.
Now if it gets 0
it prints that menu option is false break
s and goes back to beginning of the loop then to getMenuOption()
again. If you enter 1
it enters case 1
.
The problem that you mentioned:
> I get an error since the array can't hold any more Triangle objects once it's hit its limit
Is solved by adding condition
that checks length before adding to it like I did.
To exit it you would add another case
which will set run
to false
:
case 4:
run = false;
etc.
Here is repl for you to test it right away. I have changed the size of array to 2
so you can see the it stops when you reach the limit.
答案3
得分: -1
你可以尝试以下代码:
while(true){
System.out.println("1. 输入新三角形的数据。");
System.out.println("2. 按面积打印所有三角形,从小到大排序。");
System.out.println("3. 打印具有特定颜色的三角形。");
System.out.println("4. 退出程序。");
System.out.print("\n请输入数字选择选项:");
menuOption = sc.nextInt();
switch(menuOption){
case 1:
if(trianglesAdded == triangleArray.length - 1)
{
System.out.println("三角形数组已达到最大值。无法再添加更多三角形。");
return;
}
// 如果给定的边长中有一条、两条或全部为零,且三角形的颜色为1,则创建一个默认三角形
// 边长为1,颜色为1
if((side1 == 0 || side2 == 0 || side3 == 0))
{
// 问题从这里开始
triangleArray[trianglesAdded] = new Triangle();
System.out.println("创建了默认三角形");
trianglesAdded += 1;
}
// 如果给定了大于零的边长,则创建具有给定边长和颜色的三角形
else
{
triangleArray[trianglesAdded] = new Triangle(side1, side2, side3, color);
System.out.println("创建了具有指定大小和颜色的三角形");
}
break;
case 2:
...
break;
case 3:
...
break;
case 4:
...
break;
default:
System.out.println("无效的菜单选择。请重试。\n");
break;
}
}
英文:
you may try the following code
while(true){
System.out.println("1. Enter data for a new triangle.");
System.out.println("2. Print all triangles sorted by area, smallest to largest.");
System.out.println("3. Print only triangles with a specific color.");
System.out.println("4. Exit the program.");
System.out.print("\nPlease enter in a number to select an option: ");
menuOption = sc.nextInt();
switch(menuOption){
case 1:
if(trianglesAdded == triangleArray.length - 1)
{
System.out.println("The triangle array has hit the max. You are unable to add more triangles.");
return;
}
// If one, two, or all of the side lengths given are zero and the color of the triangle is 1, creates a default triangle
// with the sides being 1 and the color being 1
if((side1 == 0 || side2 == 0 || side3 == 0))
{
// Problem begins here
triangleArray[trianglesAdded] = new Triangle();
System.out.println("Default triangle created");
trianglesAdded += 1;
}
// If side lengths greater than zero were given, creates a triangle with the side lengths and color given
else
{
triangleArray[trianglesAdded] = new Triangle(side1, side2, side3, color);
System.out.println("Triangle created with specified size and color");
}
break;
case 2:
...
break;
case 3:
...
break;
case 4:
...
break;
default:
System.out.println("Invalid menu choice. Please try again.\n");
break;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论