I'm trying to write a while loop that accepts the input from the user and the test if it's positive or negative. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

I'm trying to write a while loop that accepts the input from the user and the test if it's positive or negative.

6th Nov 2016, 11:28 PM
darius mohammed
darius mohammed - avatar
8 Answers
+ 1
import java.util.Scanner; class MyClass { public static void main(String[ ] args) { int a; Scanner myVar = new Scanner(System.in); a=myVar.nextInt(); while (a>0) { System.out.println("Your input is postive"); break; } } }
7th Nov 2016, 2:40 AM
Aditya kumar pandey
Aditya kumar pandey - avatar
+ 1
import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int count; System.out.println("Enter your value:"); count = scan.nextInt(); if(count <= 0){ while (count <=0) { System.out.println("Negative value \nEnter positive value:"); count = scan.nextInt(); } } System.out.println("Positive value!"); } }
9th Nov 2016, 1:07 PM
Oleksandr Tykhonenko
Oleksandr Tykhonenko - avatar
0
why with while loop, try if block if(x<0) cout << "negative value" << endl; else cout << "positive value" << endl; where x is your input using while while(x<0){ cout << "negative valu"; break;} while(x>0){ cout << "positive value"; break; } you can also use flag variable method. But it will make you idiot.
6th Nov 2016, 11:58 PM
Aditya kumar pandey
Aditya kumar pandey - avatar
0
Thx but I want it with a while loop
7th Nov 2016, 12:06 AM
darius mohammed
darius mohammed - avatar
0
I have shown example of while loop
7th Nov 2016, 1:35 AM
Aditya kumar pandey
Aditya kumar pandey - avatar
0
You wrote if else statements I was looking for something like this, but mine not working import java.util.Scanner; class MyClass { public static void main(String[ ] args) { Scanner myVar = new Scanner(System.in); while (myVar > 0 ) { System.out.println("Your input is postive") ; Else System.out.println("put a positive number") } System.out.println(myVar.nextLine()); // help me fix it } }
7th Nov 2016, 2:32 AM
darius mohammed
darius mohammed - avatar
0
in while loop use break after printing your value is positive,otherwise it is an infinite loop.
7th Nov 2016, 2:36 AM
Aditya kumar pandey
Aditya kumar pandey - avatar
0
Thanks that is what I was trying to do.
7th Nov 2016, 2:44 AM
darius mohammed
darius mohammed - avatar