Reputation: 37
for these guidelines:
Write a loop that reads positive integers from standard input and that terminates when it reads an integer that is not positive. After the loop terminates, it prints out, separated by a space and on a single line, the sum of all the even integers read and the sum of all the odd integers read. Declare any variables that are needed.
ASSUME the availability of a variable, stdin , that references a Scanner object associated with standard input.
I wrote this code, but it the HW software will not except it due to a logical error. I cant seem to find the logical error here. can someone point out what is wrong with it?
int sumP=0;
int sumO=0;
Scanner stdin = new Scanner (System.in);
System.out.println("enter an odd or even number");
while (stdin.nextInt() >= 0){
if(stdin.nextInt()%2 == 0)
sumP+= stdin.nextInt();
else
sumO += stdin.nextInt();
}
System.out.println(sumP + " " + sumO);
Upvotes: 1
Views: 11923
Reputation: 1
int number = 1;
while (stdin.hasNextInt() && number > 0)
{
number = stdin.nextInt();
if (number % 2 == 0 && number > 0)
System.out.print(number + " ");
}
The answer to this and many other codelab exercises can be found at Java Codelab Solutions
Upvotes: 0
Reputation: 1
This worked for myprogramminglab - Java
int sum=0;
boolean areMore = true;
int negative;
while (areMore)
{
int number = stdin.nextInt();
if (number <= 0)
areMore = false;
else if (number %2 ==0 )
sum = sum + number;
else
negative = sum + number;
}
System.out.println(sum);
Upvotes: 0
Reputation: 533530
You need to save the value you have read, otherwise you will be used different values in the while loop and the addition.
int n;
while((n = stdin.readInt()) >= 0) {
// use the same value of n
Upvotes: 7