Please help with this program: "Write a program that reads from keyboard numbers and calculates their sum. If the user enters -1, the program should display the sum and terminate. -1 should be included in sum.".

I don't understand how to do reading from keyboard when i don't konw how many numberes there are and when i should and how stop?

asked 12 Apr '15, 19:25

Karolis%20Belia%C5%A1as's gravatar image

Karolis Beli...
25310
accept rate: 0%


karolis try
System.out.println(sum-1);

because in task it is given that -1 should be included in the sum

link

answered 26 Apr '15, 11:25

rahul's gravatar image

rahul
7916
accept rate: 15%

edited 29 Apr '15, 17:05

public class Solution
{
    public static void main(String[] args)   throws Exception
    {
        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
        int a;
        int sum=0;
        int i=0;
        while (i != -1){
            String s = r.readLine();
            a = Integer.parseInt(s);
            if (a != -1){
                sum+=a;
            }
            else {
                i=a;
            }
        }
        System.out.println(sum);
    }
}

here is my program it gets good reasults but can't pass the test why?

link

answered 14 Apr '15, 12:25

Karolis%20Belia%C5%A1as's gravatar image

Karolis Beli...
25310
accept rate: 0%

here is my version. also doesn't pass the test though.... may be some body know why?

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    int x = 0;
    int sum =0;

    while(x != -1){

        x = Integer.parseInt(reader.readLine());
        System.out.println(sum = sum + x);
    }
link

answered 22 Feb '17, 02:01

Dmitry%20Sky's gravatar image

Dmitry Sky
113
accept rate: 0%

edited 22 Feb '17, 02:15

int sum = 0; for (; true;) { BufferedReader a = new BufferedReader(new InputStreamReader(System.in)); String b = a.readLine(); int b1 = Integer.parseInt(b); sum = b1 + sum; System.out.println(sum); if (b.equals("-1")) break; }

link

answered 07 Nov, 22:44

Grigory's gravatar image

Grigory
1
accept rate: 0%

my code also doesn't pass the test

(07 Nov, 22:45) Grigory
Your answer
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "Title")
  • image?![alt text](/path/img.jpg "Title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Tags:

×36
×8
×4

Asked: 12 Apr '15, 19:25

Seen: 2,739 times

Last updated: 07 Nov, 22:45