CodeGym /Java Course /Module 1. Java Syntax /Examples of using a while loop

Examples of using a while loop

Module 1. Java Syntax
Level 6 , Lesson 2
Available

1. Summing numbers using a while loop

Let's write a program that reads numbers from the keyboard (as long as the user enters something that looks like a number) and then displays their sum on the screen. Here's how the code of such a program would look (we're only showing the code inside the main method).

Code Explanation
Scanner console = new Scanner(System.in);
int sum = 0;
while (console.hasNextInt())
{
   int x = console.nextInt();
   sum = sum + x;
}
System.out.println(sum); 
Create a Scanner object to read data from the console.
We will store the sum of the numbers in the sum variable.
As long as numbers are entered from the console

read the next number into the x variable.
Add x to the sum of numbers (the sum variable).

Display the calculated sum on the screen.

2. Finding the maximum number using a while loop

Our second program will also read numbers from the keyboard (as long as the user enters something number-like), but now we want to display the largest of the numbers entered. Here's how the code of such a program would look (we're only showing the code inside the main method).

Code Explanation
Scanner console = new Scanner(System.in);
int max = 0;
while (console.hasNextInt())
{
   int x = console.nextInt();
   if (x > max)
     max = x;
}
System.out.println(max); 
Create a Scanner object to read data from the console.
The max variable will store the maximum of the numbers.
As long as numbers are entered from the console

read the next number into the x variable.
Compare x and max. If x is greater than max,
update the maximum.

Display the maximum number on the screen.

Here's an interesting point: if all the numbers entered from the keyboard are negative, then the program will display 0. Which is incorrect.

As a result, the initial value of the max variable should be as small as possible.

Option 1:

You can set it equal to -2,000,000,000 (negative two billion). This isn't a bad start.

Option 2:

Assign the smallest possible int value. There's a special constant for this: Integer.MIN_VALUE;

Option 3:

Better yet, initialize max with the first number entered. This is the best option. But this will only work if the task conditions require the user to enter at least one number.

Comments (12)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
SinACosB Level 4, Delhi, India
20 May 2024
oh wow that was amazing i thought same code but then came to know its wrong as 0 will be output when all -ve lol
Grzesiek Level 9, Poland
28 March 2024
Considering option 3 from the description (the best) "Better yet, initialize max with the first number entered(...)". Scanner scanner = new Scanner(System.in); while (!scanner.hasNextInt()){ System.out.println("It's not a number. Try again."); scanner.next(); } int min = scanner.nextInt(); while(scanner.hasNextInt()){ int x = scanner.nextInt(); if(x < min){ min = x; } } System.out.println(min); It works correctly and has the most logical implementation (I think so), but it doesn't meet the 5. point that enforces "(...) then display the maximum possible value for int." - I think this point should be changed to allow two approaches, rather than forcing one.
Zhanysh Level 41, Warsaw - the best!
1 November 2023
Not sure if "Correct solution" provided meets all the criteria. When it comes to the task, really challenging 🙂
17 April 2023
That last one was hard, but it was fun.
Abdulaziz alshaikh Level 1, Saudi Arabia
8 February 2023
why is everything numbers numbers math math😪
Bryan Level 6, Canada
15 January 2023
This is so fun! Programming is an artform. My advice to others is to not let yourself get frustrated, take a step back and approach problems from a different angle if need be. I like how different programmers can have different solutions to the same problems yet achieve the same outcome. If you go to the community help section for your task you can browse other poster's code that needs work. Even if their code is not working right, it will allow you to see how others might approach the same problem.
Jennifer Olland Level 4, United States of America, United States
30 October 2023
I get this. But I hate how slow I am at it, the part that I get mad at myself for, is that it takes me more than 20 minutes to do any one of these.
Java coffee Level 5, Ireland
15 November 2024
That's what I also love about programming and to some degree, maths as well...the ability to approach and solve one problem in more than one way always fascinates me. It's definitively a creative endeavour. But I also get frustrated when I go blank when trying to solve some of these tasks, it can take me a good while to come up with a solution but the more I practice with some exercises, the better I'm becoming at getting creative with a solution.
Sal Level 5, Indonesia
17 December 2022
Have we learned about hasNextInt() before this section? Did I not pay pay attention or we are indeed supposed to search about it ourselves?
Andrew Bracero Level 24, United States of America, United States
26 February 2023
It was covered in a previous lesson regarding the Scanner object in a previous level's curriculum. The

hasNextInt()
checks to ensure that the next console input from the user is an integer in the same way that

hasNextLine()
checks to ensure that the next console input from the user is a string. There are also other ways to check user input such as

hasNextDouble()
and even

hasNext()
which just makes sure that there is a token, or any thing other than the default whitespace. Cheers.
Tobias Daniels Level 18, United States
8 December 2022
I think the last task was a little much.
🤥匹诺曹 Level 8, Jinan, United States
17 September 2022
holy shit, the last one was hard, and i did not tried it on my local complier that was 10 attempts :/