当在for循环中满足if语句中的条件时,如何打印一个结果?(When conditions in a if statement are met inside a for loop, how can I

编程入门 行业动态 更新时间:2024-10-25 19:32:04
当在for循环中满足if语句中的条件时,如何打印一个结果?(When conditions in a if statement are met inside a for loop, how can I print one result?)

基本上我有以下代码。 问题是如果满足if语句中的两个条件,我只想打印一次“Pass”。 int'res'是parts数组中所有6个元素的平均值。 因此,所有“部分”必须具有至少40的值,并且这些部分的平均值(称为“res”)也必须高于40.此时,代码显然为“6”的6个元素中的每一个输出Pass。如果它们超过40,则表示“数组”。如果“parts”数组和“res”的所有六个元素都超过或等于40,我希望这只输出Pass。

任何帮助将不胜感激!

for (int i = 0; i < 6; i++) { if (res >= 40 && parts[i] >= 40) { System.out.println("Pass"); } }

Basically I have the following code. The problem is that I only want to have "Pass" printed once if both conditions in the if statement are met. The int 'res' is an average of all 6 elements in the parts array. Therefore, all "parts" must have a value of at least 40 and the average of these parts, known as "res", must also be above 40. At the moment the code obviously outputs Pass for each of the 6 elements of the "parts" array if they are over 40. I want this to just however output Pass once if all six elements of the "parts" array and "res" are over or equil to 40.

Any help will be gratefully appreciated!

for (int i = 0; i < 6; i++) { if (res >= 40 && parts[i] >= 40) { System.out.println("Pass"); } }

最满意答案

2件事:

1)你看起来只是在检查一个否定的情况。 如果您发现任何小于40的值, break并且不打印“通过”。 如果每个元素超过40且res超过40,则您希望继续,直到找到一个未完成或完成列表的元素。 如果你通过整个列表并且没有一个失败,你知道你可以打印“通过”。

2)res在您提供的循环中没有变化。 如果你在循环中更改它,这只是示例代码,没关系。 但是,如果你不是,你应该只是在循环之外检查一次。

boolean print = true; for (int i = 0; i < 6; i++) { if (res < 40 | parts[i] < 40) { print = false; break; } } if(print) System.out.println("Pass");

2 things:

1) You look like you're just checking for a negative case. If you find any values that are less than 40 you want to break and not print "Pass". If each element is over 40 and res is over 40 you want to continue until you either find one that isn't or finish through the list. If you get through the whole list and none failed you know you can print "Pass".

2) res isn't changing in your loop as you supplied it. If you are changing it in the loop and this is just example code that's fine. But if you're not you should really just check it once outside of the loop.

boolean print = true; for (int i = 0; i < 6; i++) { if (res < 40 | parts[i] < 40) { print = false; break; } } if(print) System.out.println("Pass");

更多推荐

本文发布于:2023-08-04 20:10:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1421395.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   条件   conditions   statement   result

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!