Every time i run the loop the count is off by 1 and one of the inputs is not being added to the sum. Heres my code :
import java.util.Scanner;
public class InputSequence
{
public static void main (String[] args)
{
int sum = 0;
int count = 1;
int input = 0;
System.out.println("Enter integers, enter non integer to compute sum of input");
Scanner scan = new Scanner(System.in);
while (scan.hasNextInt())
{
input = scan.nextInt();
if ( scan.hasNextInt())
{
sum = input + sum;
count++;
}
else
{
System.out.println("You have entered " + count + " integers, the sum is " + sum);
}
}
}
}
1
Expert's answer
2012-11-23T03:00:22-0500
this code works correct import java.util.Scanner;
public class InputSequence
{ public staticvoid main (String[] args) { int sum =0; int count =0; int input;
System.out.println("Enter integers, enter non integer to computesum of input");
Scanner scan = new Scanner(System.in);
while(scan.hasNextInt()) { input =scan.nextInt(); sum =input + sum; count++; }
System.out.println("You have entered " + count + "integers, the sum is " + sum); } }
Comments
Leave a comment