使用简单的布尔值时遇到麻烦

时间:2013-05-14 18:40:08

标签: java boolean conditional

对不起,如果这是一个愚蠢的问题,但我完全是新手,只是尝试我的手。 我的代码卡住....在此之后,程序结束,无论是选择1还是2。我知道它的一些简单的东西我不知道......任何输入都值得赞赏我复制并粘贴了我认为问题所在的部分。

    System.out.println("Is this information correct? Enter 1 if it is correct, and 2 to change");
    Scanner inputCorrect = new Scanner(System.in);
    int pick = inputCorrect.nextInt();
    boolean isCorrect = false;

    while (isCorrect = false){

          while (!(pick == 1) && (!(pick ==2)))
              System.out.println("That is not a valid entry please try again");

              if (pick == 1){

                  isCorrect = true;
              }

              if (pick == 2){
                  System.out.println("Enter 1 to change your name, 2 to change your age or 3 to change your gender");
                  Scanner inputChange = new Scanner(System.in);
                  int change = inputChange.nextInt();

                    if (change ==1){
                        Scanner inputNewName = new Scanner(System.in);
                        System.out.println("Enter the correct name: ");
                        String correctedName = inputNewName.next();
                        you.setName(correctedName);
                        System.out.println(you);
                        isCorrect = true;
                    }

                    if (change ==2) {
                        Scanner inputNewAge = new Scanner(System.in);
                        System.out.println("Enter the correct age: ");
                        int correctedAge = inputNewAge.nextInt();
                        you.setAge(correctedAge);
                        System.out.println(you);
                        isCorrect = true;

                    }

                    if (change == 3) {
                        Scanner inputNewGender = new Scanner (System.in);
                        System.out.println("Enter the correct gender: ");
                        char correctedGender = inputNewGender.next().charAt(0);
                        you.setGender(correctedGender);
                        System.out.println(you);
                        isCorrect = true;

                    }   
          }     
      } 

3 个答案:

答案 0 :(得分:10)

在你的while循环中

while (isCorrect = false){

您正在使用分配运算符=,因此它总是错误的。

您希望比较运算符==比较值是否相同。

while (isCorrect == false){

由于它已经是boolean,您可能只想自己使用isCorrect

while (!isCorrect)

答案 1 :(得分:3)

您在while语句表达式中使用赋值运算符,该运算符将始终计算为false。请使用==运算符来比较boolean

while (isCorrect == false){

或更好

while (!isCorrect){

答案 2 :(得分:2)

您可以通过以下方式帮助自己:

 while( false == isCorrect )

如果错误输入相等运算符,则会抛出编译错误。