返回错误值的简单java程序

blmhpbnm  于 2021-09-13  发布在  Java
关注(0)|答案(3)|浏览(404)

你好,我正在复习java练习。我有一个非常简单的程序:有两个int值,以及一个布尔变量。如果其中一个值为负值,另一个值为正值,则程序将返回true。但是,如果布尔变量为true,则程序只能在两个int值均为负值时返回true。
我已经用一堆int值对此进行了测试,但是一旦我给这个方法(1,-1)的值,以及布尔值设置为true,程序似乎就会崩溃。任何帮助或解释都将不胜感激。

  1. public static void main(String[] args) {
  2. System.out.println(posNeg(1,-1,true));
  3. }
  4. public static String posNeg(int a, int b, boolean negative){
  5. if(negative && (a<0 && b<0)){
  6. return "true";
  7. }else if(!negative && (a<0 && b>0) || (a>0 && b<0)){
  8. return "true";
  9. }
  10. return "false";
  11. }
4jb9z9bj

4jb9z9bj1#

您的代码因以下原因而中断: && 优先。
|| 括号内的条件:

  1. public static void main(String[] args) {
  2. System.out.println(posNeg(1,-1,true));
  3. }
  4. public static String posNeg(int a, int b, boolean negative){
  5. if(negative && (a<0 && b<0)){
  6. return "true";
  7. }else if(!negative && ((a<0 && b>0) || (a>0 && b<0))){
  8. return "true";
  9. }
  10. return "false";
  11. }
t1rydlwq

t1rydlwq2#

&&具有比| |更高的优先级,因此在else if条件下,即!负&&(a<0&&b>0)| |(a>0&&b<0)首先计算此条件!负&&(a<0&&b>0),然后使用res | |(a>0&&b<0)对结果进行评估。
在你的例子中,我想你首先要计算| |,然后&,所以只需在括号中加上这样一个括号!负&&((a<0&&b>0)| |(a>0&&b<0)),因此首先计算括号内的条件,然后使用&&

  1. public class Main
  2. {
  3. public static void main(String[] args) {
  4. System.out.println(posNeg(1,-1,true));
  5. }
  6. public static String posNeg(int a, int b, boolean negative){
  7. if(negative && (a<0 && b<0)){
  8. return "true";
  9. }else if(!negative && ((a<0 && b>0) || (a>0 && b<0))){
  10. return "true";
  11. }
  12. return "false";
  13. }
  14. }
展开查看全部
2q5ifsrm

2q5ifsrm3#

  1. public static void main(String[] args) {
  2. System.out.println(posNeg(1,-1,false));
  3. }

公共布尔posneg(inta,intb,布尔负){if(负)返回(a<0&&b<0);else返回((a<0&&b>0)| |(a>0&&b<0));)

相关问题