60 709
Assignments Done
97,9%
Successfully Done
In April 2018

Answer to Question #19229 in Java | JSP | JSF for Seamus MacKie

Question #19229
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);
}
}
}
}
Expert's answer
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);
}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions