Issue
Need to fix my program. Write a java program using WHILE LOOP: how many positive and negative numbers? User prompt the integers and ends with number 0. You will see in my output that if user enter 1 2 3 -1 -2 -3 0 My output answer: 2 positive / 3 negative. The first positive number is not count. Please let me know where is my error. I cannot find it.
Scanner input= new Scanner(System.in);
//int data;
int count = 0;
int negative=0;
int positive =0;
System.out.print("Enter an integer (Program ends if enter 0): ");
int data = input.nextInt();
while (data !=0) {
System.out.print("Enter an integer (Program ends if enter 0): ");
data=input.nextInt();
//count++;
if (data < 0){
negative++;
}else if (data > 0){
positive++;
}
count++;
}
System.out.println(positive + " positive numbers");
System.out.println(negative + " negative numbers");
}
}
output:
run:
Enter an integer (Program ends if enter 0): 1
Enter an integer (Program ends if enter 0): 2
Enter an integer (Program ends if enter 0): 3
Enter an integer (Program ends if enter 0): -1
Enter an integer (Program ends if enter 0): -2
Enter an integer (Program ends if enter 0): -3
Enter an integer (Program ends if enter 0): 0
2 positive numbers
3 negative numbers
BUILD SUCCESSFUL (total time: 11 seconds)
Solution
You are over riding the first input, after entering into the loop.
- You are reading the input and checking if input is not equal to zero or not
- After entering into the loop again you are reading the input from scanner and storing it to variable data(here the previous data is getting overridden)
updated Code:
Scanner input = new Scanner(System.in);
// int data;
int count = 0;
int negative = 0;
int positive = 0;
System.out.print("Enter an integer (Program ends if enter 0): ");
int data = input.nextInt();
while (data != 0) {
// count++;
if (data < 0) {
negative++;
} else if (data > 0) {
positive++;
}
count++;
System.out.print("Enter an integer (Program ends if enter 0): ");
data = input.nextInt();
}
System.out.println(positive + " positive numbers");
System.out.println(negative + " negative numbers");
Answered By - Manjunath H M
Answer Checked By - Katrina (JavaFixing Volunteer)