Java Codelab While语句

时间:2016-02-10 23:08:59

标签: java java.util.scanner

有人可以解释为什么当我输入-99时,程序不会停止? 当我输入-99作为第一个输入时,程序停止,但如果我先输入1然后输入-99秒,则程序不会停止

import java.util.Scanner;

   public class TESTTEST {
       public static void main(String [] args) {
         // creates the scanner
        Scanner input = new Scanner(System.in);

        int number;
        int max=0;
        int min=0;
        int counter = 0;

        System.out.print("Enter an integer (-99 to stop): ");
          number = input.nextInt();
          {
while (number != -99) {
    System.out.print("Enter an integer (-99 to stop): ");
          number = input.nextInt();

         if (number> max ){
             number = max;  
         }
          else if (number<max ) {
                 number = min;
           }
        }

        System.out.println("max value is " +max);
        System.out.println("min value is "+min);

    }
}
   }

1 个答案:

答案 0 :(得分:1)

您倒置了numbermax / min

if (number> max ){
         number = max;  //Since max = 0, number turns into 0
     }
      else if (number<max ) {
             number = min; //Same thing here
       }
    }

    System.out.println("max value is " +max);
    System.out.println("min value is "+min);

}

切换它们:

if (number> max ){
         max = number;
     }
      else if (number<max ) {
             min= number;
       }
    }

    System.out.println("max value is " +max);
    System.out.println("min value is "+min);

}