Why can't we use else statement with while in java, whereas if need be what is the best possible alternative? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why can't we use else statement with while in java, whereas if need be what is the best possible alternative?

I've been studying python, java and some other languages. I've come across some commonalities and some differences which I understand to the best of my potentials. But I've come to know that we can't use else statement following a while loop in java, like I used to code in python. For instance I want to make a code that takes a input (let's say random integers) from a user, the user may wants to input as many as he can(I'd use while loop for such repeated action), or else he'd just enter 1 numbers. So, in this program I could use a while loop followed by a else statement if I were to code in python. But my main question is, if I were to code this approach in java, why can't I do it, and what is the best alternative?

2nd Jun 2020, 4:29 PM
Ehtisham Rehmat
Ehtisham Rehmat - avatar
4 Answers
0
Hello Ehtisham Rehmat else belongs in all languages to if. if (your condition) do this else do that. If you want a while loop you can use an if/else statement inside the loop. Or you can use a break statement inside the loop which stops the loop.
2nd Jun 2020, 4:36 PM
Denise Roßberg
Denise Roßberg - avatar
0
Denise Roßberg and 𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 I am glad to see your responses. I understand else follows if condition in all languages. Actually my question was as if I wanted to write a code as follow: (it's in python) n = input("write multiple for multiple integer inputs: ") my_list =[] While n == "multiple": num =int(input()) my_list.append(num) # And whatever is the following code in the while body else: num = int(input("seems you've to enter an integer")) print(f"You've entered {num} in your input") So, if I were to design this approach in Java what is best alternative?
2nd Jun 2020, 5:02 PM
Ehtisham Rehmat
Ehtisham Rehmat - avatar
0
for your example if ( multiple ) { while(! end) { // get input1 } } else { // get input2 } but python works different while(! end) { // get input1 } if (end) { // something after normal end of while } it has sense if while ends with break, but end is stil not true
3rd Jun 2020, 1:01 AM
zemiak
0
zemiak thanks brother, I really appreciate your help
3rd Jun 2020, 11:25 AM
Ehtisham Rehmat
Ehtisham Rehmat - avatar