Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

While loops with numbers in Java

my code won’t output what it should the instructions:
Read integers from input until an integer is read that is not in the range -20 to 25, both inclusive. Output the total number of integers read, including the integer that causes reading to stop. End with a newline.

Ex: If the input is -13 -49 -17 -16 -11, then the output is:

Number of integers read: 2
My code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import java.util.Scanner;

public class CountRead {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
      int inputValue;
        int countRead;

      inputValue = scnr.nextInt();
      countRead = 0;
      
      while( (inputValue >= -20) || (inputValue <=  25)){
         countRead++;
         inputValue = scnr.nextInt();
         
        
      }
      
      System.out.println("Number of integers read: " + (countRead +1 )); 

   }
}

>Solution :

Look at this statement very, very closely:

while( (inputValue >= -20) || (inputValue <=  25)) {

And specifically what the while statement is evaluating;

((inputValue >= -20) || (inputValue <=  25))

If inputValue is say… -49, what does that expression evaluate to? true for false?

Be careful!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading